C Programm to insert element into an Array

In this c programming example we will learn how to insert an element in-between an array.

  • Define length of the array and assign to variable n
  • Now enter elements for the array and place from position 0 to n-1
  • Now enter the position where we want to insert new element
  • Now ask user to enter the value to be insert
  • Place the variable in the given position and print the final array
#include<stdio.h>
#define max 20
void main()
{
 int p[max], n,i,k,j;
 printf("Enter length of array:");
 scanf("%d",&n);
 printf("Enter %d elements of array\n",n);
 for(i=0;i<=n-1;i++ )
 scanf("%d",&p[i]);
 printf("\nThe array is:\n");
 for(i = 0;i<=n-1;i++)
 printf("%d\n",p[i]);
 printf("\nEnter position where to insert:");
 scanf("%d",&k);
 k--;/*The position is always one value higher than the
 subscript, so it is decremented by one*/
 for(j=n-1;j>=k;j--)
 p[j+1]=p[j];
 /* Shifting all the elements of the array one position down
from the location of insertion */
 printf("\nEnter the value to insert:");
 scanf("%d",&p[k]);
 printf("\nArray after insertion of element: \n");
 for(i=0;i<=n;i++)
 printf("%d\n",p[i]);
}

 

Output:

Enter length of array:5
Enter 5 elements of array
12
23
12
14
25

The array is:
12
23
12
14
25

Enter position where to insert:3

Enter the value to insert:95

Array after insertion of element:
12
23
95
12
14
25