Inserting elements in an array using C Language

CServer Side ProgrammingProgramming

We can insert the elements wherever we want, which means we can insert either at starting position or at the middle or at last or anywhere in the array.

After inserting the element in the array, the positions or index location is increased but it does not mean the size of the array is increasing.

The logic used to insert element is 

  • Enter the size of the array

  • Enter the position where you want to insert the element

  • Next enter the number that you want to insert in that position

for(i=size-1;i>=pos-1;i--)
   student[i+1]=student[i];
   student[pos-1]= value;

Final array should be printed using for loop.

Program

 Live Demo

#include<stdio.h>
int main(){
   int student[40],pos,i,size,value;
   printf("enter no of elements in array of students:");
   scanf("%d",&size);
   printf("enter %d elements are:\n",size);
   for(i=0;i<size;i++)
      scanf("%d",&student[i]);
   printf("enter the position where you want to insert the element:");
   scanf("%d",&pos);
   printf("enter the value into that poition:");
   scanf("%d",&value);
   for(i=size-1;i>=pos-1;i--)
      student[i+1]=student[i];
   student[pos-1]= value;
   printf("final array after inserting the value is\n");
   for(i=0;i<=size;i++)
      printf("%d\n",student[i]);
   return 0;
}

Output

enter no of elements in array of students:6
enter 6 elements are:
12
23
34
45
56
67
enter the position where you want to insert the element:3
enter the value into that poition:48
final array after inserting the value is
12
23
48
34
45
56
67
raja
Published on 05-Mar-2021 16:21:39
Advertisements