Insertion of an element at a specific index, write a c program
Insertion of an element at a specific index, write a c program
Insertion of an element at a specific index, write a c program
Enter the size of the array: 4 Enter the elements of the array: 1 2 3 4 5 Enter the index at which to insert element: 3 Enter the element to be inserted: 998
Array after insertion: 1 2 3 998 4
#include <stdio.h>
int main() {
int n; // size of array
int arr[100]; // array
int index; // index at which to insert element
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array: ");
for (int i = 0; i <= n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the index at which to insert element: ");
scanf("%d", &index);
int element; // element to be inserted
printf("Enter the element to be inserted: ");
scanf("%d", &element);
for (int i = n; i > index; i--) {
arr[i] = arr[i-1];
}
arr[index] = element;
printf("Array after insertion: ");
for (int i = 0; i <= n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Enter the size of the array: 4
Enter the elements of the array: 1 2 3 4 5
Enter the index at which to insert element: 3
Enter the element to be inserted: 998
Array after insertion: 1 2 3 998 4
This program takes the size of the array as input and creates an array of that size. The user is prompted to enter the elements of the array and the index at which they want to insert a new element. The user is also prompted to enter the element they want to insert. The program then shifts all elements after the specified index one position to the right and inserts the new element at the specified index. Finally, the program prints the modified array.
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.