C Program to insert an element in an array
C Program to insert an element in an array.
Suppose there is an array of length N . We want to insert an element in the array at index i (0<=i<=N-1). After inserting element number of element will be increased by 1. To insert an element in array at the index i we have to shift all elements of array from i to N-1. to next index . An element from index position j will be moved to j+1.
For example, suppose there is an array ” a ” of length of 8 which contains 5 elements from a[0] to a[4]. We want to insert 25 at index position a[3]. So we have to move every elements from a[3] to a[4] to next index position in the array.
Move a[4] to a[5]
Move a[3] to a[4]
Insert 25 at a[3]
C Program to insert an element in an array : Source Code
/****************************************************************************** C Program to insert an element in an array https://bptutorials.com *******************************************************************************/ #include <stdio.h> #include <conio.h> int main(){ int arr[400], totalElement, cntr, element, indexPos; printf("Enter number of total elements in array: "); scanf("%d", &totalElement); printf("Enter %d numbers \n", totalElement); for(cntr = 0; cntr < totalElement; cntr++){ scanf("%d", &arr[cntr]); } printf("Enter number to be inserted\n"); scanf("%d", &element); printf("Enter index position where you want to insert an element\n"); scanf("%d", &indexPos); /* Moving all elements right of index position by one position */ for(cntr = totalElement; cntr > indexPos; cntr--){ arr[cntr] = arr[cntr-1]; } arr[indexPos] = element; /* Print array after inserting element */ printf("Updated Array\n"); for(cntr = 0; cntr < totalElement + 1; cntr++){ printf("%d ", arr[cntr]); } getch(); return 0; }
Output :
Enter number of total elements in array: 6 Enter 6 numbers 15 10 25 7 9 23 Enter number to be inserted 14 Enter index position where you want to insert an element 5 Updated Array 15 10 25 7 9 14 23
