Here is a C program to insert an element in an array at given position. Given an array of length N, we have to insert an element in array at index i (0 <= i <= N-1). After inserting an element, the number of elements in array will increase by one.
All elements of array are stored in consecutive memory location. To insert an element at index i in array we have to shift all elements from index i to N-1 to next index. An element at index k, will be moved to index k+1.
For Example
Suppose we have an array "inputArray" of length 10, which contains 7 elements from inputArray[0] to inputArray[6]. We have to insert 15 at position inputArray[3].Move every element from inputArray[3] to inputArray[6] to next index in array.
Move inputArray[6] to inputArray[7],
Move inputArray[5] to inputArray[6],
Move inputArray[4] to inputArray[5],
Move inputArray[3] to inputArray[4].
Now, insert 15 at inputArray[3].
- Move all elements between index I to M-1 to next index(including index I and M-1).
- Move inputArray[j] to inputArray[j + 1], I <= j <= M-1.
- Insert S at inputArray[I].
- Now, inputArray contains M+1 elements from index 0 to M.
C program to insert an element in array
Below program first takes number of elements(elementCount) and 'elementCount' array elements as input from user. Then, it takes the number to be inserted(element) in array and index of insertion(index) as input from user. Then using a for loop, it shifts all the elements after 'index' by one position as explained above. After shifting, it inserts 'element' at index location.
#include <stdio.h> int main(){ int inputArray[500], elementCount, counter, element, index; printf("Enter number of elements in array: "); scanf("%d", &elementCount); printf("Enter %d numbers \n", elementCount); for(counter = 0; counter < elementCount; counter++){ scanf("%d", &inputArray[counter]); } printf("Enter number to be inserted\n"); scanf("%d", &element); printf("Enter index where you want to insert\n"); scanf("%d", &index); for(counter = elementCount; counter > index; counter--){ inputArray[counter] = inputArray[counter-1]; } inputArray[index] = element; printf("Updated Array\n"); for(counter = 0; counter < elementCount + 1; counter++){ printf("%d ", inputArray[counter]); } return 0; }Output
Enter number of elements in array: 6 Enter 6 numbers 1 2 3 4 5 6 Enter number to be inserted 9 Enter index where you want to insert 3 Updated Array 1 2 3 9 4 5 6
Enter number of elements in array: 4 Enter 4 numbers 0 1 0 1 Enter number to be inserted 5 Enter index where you want to insert 0 Updated Array 5 0 1 0 1
Related Topics