C Program to Insert Element at Specific Position in Array
Write C Program to Insert Element at Specific Position in Array
// C Program to Insert Element at Specific Position in Array #include <stdio.h> int main() { int A[] = {1, 2, 45, 34, 54, 24, 52, 75}; int i, x, pos,n; n = sizeof(A) / sizeof(A[0]); printf("Array Elements :--> "); for (i = 0; i < n; i++) printf("%d ", A[i]); printf("\nEnter Element to Insert :--> "); scanf("%d",&x); printf("Enter Position to Insert At :--> "); scanf("%d",&pos); // increase the size by 1 n++; if(pos > n) { printf("\nInvalid Position"); } else { // shift elements forward for (i = n; i >= pos; i--) A[i] = A[i - 1]; // insert x at pos A[pos - 1] = x; printf("\nArray After Insertion :--> "); for (i = 0; i < n; i++) printf("%d ", A[i]); } return 0; }
Output:
Run 1:
Array Elements :--> 1 2 45 34 54 24 52 75
Enter Element to Insert :--> 111
Enter Position to Insert At :--> 2
Array After Insertion :--> 1 111 2 45 34 54 24 52 75
Run 2:
Array Elements :--> 1 2 45 34 54 24 52 75
Enter Element to Insert :--> 111
Enter Position to Insert At :--> 12
Invalid Position