C program to insert an element in an array

C program to insert an element in an array at a specified location/position

This C program is to insert an element in an array at a specified location/position.For example, if an array a consists of elements a={7,8,12,3,9} and if we want to insert element 27 at position 3 then the new array would be a={7,8,12,27,3,9} (as array starts from index 0).

Logic

We start to iterate from the back.The reason for this is so that all the elements after the element which is inserted will be shifted by one place to the right.

Dry Run of the Program

Take input array ‘a’ and no of elements(n) as 5

Let us take elements for array a={7,8,12,3,9}.

Let us take an element as 27 which is to be inserted at position 3.

1st iteration for(i=n-1;i>=pos;i–)  i.e. for(i=5-1;i>=3;i–) i.e. for(i=4;4>=3;i–)

a[i+1]=a[i] i.e. a[4+1]=a[4] i.e. a[5]=a[4] i.e. a[5]=9

2nd iteration for(i=n-1;i>=pos;i–)  i.e. for(i=3;i>=3;i–) i.e. for(i=3;3>=3;i–)

a[i+1]=a[i] i.e. a[3+1]=a[3] i.e. a[4]=a[3] i.e. a[4]=3

Now we come out of the for loop as i(2) is less than pos(3)

n=n+1 i.e. n=5+1 i.e n=6 //We are increasing the no of elements

a[pos]=number i.e. a[3]=27  // number= no to be inserted 

Hence our new array would be a={7,8,12,27,3,9}.

Program

#include<stdio.h>
 
void main() 
{
    int a[100],i,n,number,pos;
 
    printf("\nEnter no of elements\n");    
    scanf("%d",&n);
    
    printf("Enter the elements\n");
    for (i=0;i<n;i++) 
    {
        scanf("%d",&a[i]);
    }
    
    printf("Elements of array are\n");
    for(i=0;i<n;i++) 
    {
        printf("a[%d] = %d\n",i,a[i]);
    }

    printf("Enter the number which you want to insert\n");
    scanf("%d",&number);
    printf("Enter the position where you want to insert the number\n");
    scanf("%d",&pos);
    for(i=n-1;i>=pos;i--)
    {
        a[i+1]=a[i];
    }
    n=n+1;
    a[pos]=number;
    printf("\nOn inserting new array we get is\n");
    for(i=0;i<n;i++) 
    {
        printf("a[%d] = %d\n",i,a[i]);
    }
}

Output

Share Me!