The Program in C to insert an element in 1-d array(unsorted) at the given position is given below:
#include <stdio.h>
void insert_at_position(int arr[], int size, int position, int element) {
int i;
for (i = size - 1; i >= position; i--) {
arr[i + 1] = arr[i];
}
arr[position] = element;
}
int main() {
int arr[100], size, position, element;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array: ");
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Enter the position at which the element is to be inserted: ");
scanf("%d", &position);
printf("Enter the element to be inserted: ");
scanf("%d", &element);
insert_at_position(arr, size, position, element);
size++;
printf("Array after inserting the element at position %d: ", position);
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Enter the size of the array: 3
Enter the elements of the array: 2
5
1
Enter the position at which the element is to be inserted: 2
Enter the element to be inserted: 7
Array after inserting the element at position 2: 2 5 7 1
Pro-Tips💡
This program prompts the user to enter the size of an array, then uses a for loop to read the elements of the array.
After that, it prompts the user to enter the position and the element to be inserted. Then it calls a function named insert_at_position()
that takes the array, its size, position
and element as its arguments, in the function, it uses a for loop to shift all the elements of the array one position towards the right, starting from the given position
and finally, it assigns the element to the position.
The size of the array is increased by 1, to accommodate the new element. After that, it uses another for loop to print the array after inserting the element.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.