We can insert elements at any position, which means we can insert at the beginning, middle, last or anywhere in the array.
After inserting an element into the array, the position or index position increases, but it does not mean that the size of the array increases.
The logic of inserting elements is−
Input the size of the array
Input the element to be inserted position
Next enter the number you want to insert at that position
for(i=size-1;i>=pos-1;i--) student[i+1]=student[i]; student[pos-1]= value;
The final array should be printed using a for loop.
Live demonstration
#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:</p><p>",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</p><p>"); for(i=0;i<=size;i++) printf("%d</p><p>",student[i]); return 0; }
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
The above is the detailed content of Insert elements into array using C language. For more information, please follow other related articles on the PHP Chinese website!