In this tutorial, we will learn to write C program to insert an element at the given location in an array. To insert an element at a given location first we have to go to that location and then shift each element towards the right. Or we can also do something like shifting the elements towards right till we haven’t reached the location where we have to reach.
Programming logic to insert an element in array at given location
- Our program will take size of the array first and then elements to insert in the array.
- Now it will ask the new element and location where you want to insert in the array.
- To insert an element at a given location first we will shift the elements toward right by one position till we reach the location where we have to insert element.
- Once we reached at the location, then we will insert the element at the given location.
C Program to insert element at a given location in array
#include <stdio.h>
void main() {
int loc, i, n, value;
// Heading for the program
printf("=== C Program to Insert Element at given location in Array ===\n");
// Input size of the array
printf("Enter the size of an Array: ");
scanf("%d", &n);
int arr[n]; // Declaring the array with the given size
// Input elements for the array
for(i = 0; i < n; i++) {
printf("Please give value for index %d: ", i);
scanf("%d", &arr[i]);
}
// Input the value to insert and the position
printf("Please give a number to insert at given location: ");
scanf("%d", &value);
printf("Please enter the location to insert a new element: ");
scanf("%d", &loc);
// Inserting the element at the specified location
for (i = n - 1; i >= loc - 1; i--) {
arr[i + 1] = arr[i];
}
arr[loc - 1] = value; // Insert the value at the specified position
// Output the new array after insertion
printf("After insertion, the new array is:\n");
for (i = 0; i <= n; i++) {
printf("%d ", arr[i]);
}
}
Output
=== C Program to Insert Element at given location in Array ===
Enter the size of an Array: 6
Please give value for index 0: 4
Please give value for index 1: 3
Please give value for index 2: 1
Please give value for index 3: 2
Please give value for index 4: 3
Please give value for index 5: 4
Please give a number to insert at given location: 7
Please enter the location to insert a new element: 3
After insertion, the new array is:
4 3 7 1 2 3 4
What did you think?