Insert an Element in an Array
Here, you will get a program to insert an element in an array in c language. In this program you can inserts an element into the ArrayList at the specified index. If you want you can insert element at the beginning, or in between, or at the end.
Follow the following steps to complete the program:-
Step 1 Create an array list and input some numbers.
Step 2 Input location and value of element (to insert in Array List).
Step 3 Start a loop till location to be found, insert new value, and continue loop till end and shift element to next position.
Step 4 Print the array list.
Program to Insert an Element in an Array
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 | #include<stdio.h> int main() { int i, ar[50], k,n,item; clrscr(); printf("\nEnter the size of the array : "); scanf("%d",&n); printf("\nEnter elements of array : "); for(i=0;i<=(n-1);i++) { scanf("%d",&ar[i]); } printf("\nEnter the location of the element to insert : "); scanf("%d",&k); printf("\nEnter element value to insert : "); scanf("%d",&item); i=n-1; while(i>=k-1) { ar[i+1]=ar[i]; i--; } ar[k-1]=item; printf("\n\n\nArray elements are : "); for(i=0;i<=n;i++) { printf("%d ", ar[i]); } getch(); return 0; } |
Output
Enter the size of the array : 5
Enter elements of array : 2 4 8 10 12
Enter the location of the element to insert : 3
Enter element value to insert : 6
Array elements are : 2 4 6 8 10 12
Check out our other C programming Examples