C Program to Insert an Element in a Specified Position in Array is a program which inserts an element at a specific position in the array.

How to insert an element at a specified position in array?
We know the concept of the array in c. The array has an index using this concept we insert the element at a specified position.
We take an element and it’s position from a user. And use the position as an index of the array and insert an element in the array at that index. Print the array to see the element is stored at a specified position.

Algorithm to Insert an Element in a Specified Position in Array

  1. Define array. a[10]
  2. Take element and it’s position input from user. No, pos
  3. Traverse the array
    For i = 0 to end
    If a[i] == pos
    Insert element. a[i]=pos
    Break
    If a[i] == end
    Stop
  4. Print array

C Program to Insert an Element in a Specified Position in a given Array

#include<stdio.h>

main()

{

int i,size,position,insitem;

printf("Enter size\n");

scanf("%d",&size);

int a[size],temp[size+1];

printf("Enter numbers in array\n");

for(i=0;i<size;i++)

{

scanf("%d",&a[i]);

}

printf("Enter element to be inserted\n");

scanf("%d",&insitem);

printf("Enter position for an element to be inserted\n");

scanf("%d",&position);

position=position-1;

for(i=0;i<=size;i++)

{
if(i<position)
{

temp[i]=a[i];

}
if(i>position)
{
temp[i]=a[i-1];

}

if(i==position)

{

temp[i]=insitem;
}

}


printf("Array after inserting %d\n",insitem);
for(i=0;i<=size;i++)

{
printf("%d\n",temp[i]);

}

}

Output :

Insert element in array

Write A Comment