Monday, 12 December 2016

C program to insert an element into an array using pointers

In C, an array is a static data structure to store data of similar data type. But using pointers the array can be made dynamic. That is, the array size can be changed to accommodate more values as and when necessary. Using pointers the storage space is not wasted.

In this program, malloc() function is used to allocate memory dynamically for the array and afterwards realloc() function is used to increase the memory for array to insert more values into the array.

//Program to insert elements into an array
#include<stdio.h>
#include<conio.h>
#include<alloc.h>

int size;
main()
{
  int pos, n, i, size, j, choice;
  int *arr;

  clrscr();
  printf("Enter the number of elements in the array\n");
  scanf("%d",&size);
  arr=(int *)malloc(size*sizeof(int));
  printf("Enter the elements in the array\n");
  for(i=0;i<size;i++)
  scanf("%d",(arr+i));

  do
  {
    printf("Enter the number to be inserted into the array\n");
    scanf("%d",&n);
    printf("Enter the position at which the number is to be inserted\n");
    scanf("%d",&pos);
    printf("The elements in the array before insertion\n");
    for(i=0;i<size;i++)
     printf("%d\n",*(arr+i));

    ++size;
    arr=(int *)realloc(arr, size+1);
    for(i=size-1,j=i-1;i>pos;i--,j--)
     *(arr+i)=*(arr+j);
     *(arr+pos)=n;

    printf("The elements in the array after insertion\n");
    for(i=0;i<size;i++)
    printf("%d\n",*(arr+i));
   printf("Do you want to insert more elements? 1.Yes 2. No\n");
   scanf("%d",&choice);
  }while (choice==1);
    getch();
}

/*
OUTPUT
-------
Enter the number of elements in the array
4
Enter the elements in the array
1
2
3
4
Enter the number to be inserted into the array
5
Enter the position at which the number is to be inserted
0
The elements in the array before insertion
1
2
3
4
The elements in the array after insertion
5
1
2
3
4

Do you want to insert more elements? 1.Yes 2. No
1
Enter the number to be inserted into the array
6
Enter the position at which the number is to be inserted
5
The elements in the array before insertion
5
1
2
3
4
The elements in the array after insertion
5
1
2
3
4
6
Do you want to insert more elements? 1.Yes 2. No
1
Enter the number to be inserted into the array
7
Enter the position at which the number is to be inserted
3
The elements in the array before insertion
5
1
2
3
4
6
The elements in the array after insertion
5
1
2
7
3
4
6

Do you want to insert more elements? 1.Yes 2. No
2

*/

No comments:

Post a Comment