Here is the simple C program to insert an element in a one dimensional array.
The array should be in ascending order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
#include<stdio.h> int main() { int a[20],n,x,i,pos=0; printf("Enter size of array:"); scanf("%d",&n); printf("Enter the array in ascending order:\n"); for(i=0;i<n;++i) scanf("%d",&a[i]); printf("\nEnter element to insert:"); scanf("%d",&x); for(i=0;i<n;++i) if(a[i]<=x&&x<a[i+1]) { pos=i+1; break; } for(i=n+1;i>pos;--i) a[i]=a[i-1]; a[pos]=x; printf("\nArray after inserting element:"); for(i=0;i<n+1;i++) printf("%d ",a[i]); return 0; } |
Output
Enter size of array:6
Enter the array in ascending order:
1 2 4 5 6 7
Enter element to insert:3
Array after inserting element:1 2 3 4 5 6 7