To insert an element in an array in C, you can follow these steps:
- Declare a one-dimensional array of some fixed capacity.
- Take the size of the array as input from the user.
- Define array elements, taking each element as input from the user.
- Get the number to be inserted.
- Get the position where the element needs to be inserted.
- Shift all elements to one position forward from the specified position.
- Insert the element in the specified position.
C program to insert an element in an array
#include <stdio.h>
void main(){
int arr[3], i, found, insert, pos;
printf("Enter the elements in the array: \n");
for (int i = 0; i < 2; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the element you want to insert: ");
scanf("%d",&insert);
printf("Enter the index at which you want to insert: ");
scanf("%d",&pos);
for (int i = 1; i >=pos; i--)
{
arr[i+1] = arr[i];
}
arr[pos] = insert;
for (int i = 0; i <3; i++)
{
printf("%d\n",arr[i]);
}
}
Enter the elements in the array: 1 2
Enter the element you want to insert: 3
Enter the index at which you want to insert: 1 1 3 2
Explanation:
- The program prompts the user to enter two integers into an array (assuming
for
loop should run fori < 3
to match array size). - It then takes user input for the element (
3
) and the index (1
) at which the user wants to insert a new element. - Using a loop, it shifts elements to the right starting from the specified index to make space for the new element.
- It inserts the user-specified element at the specified index in the array.
- The final array is printed, showing the result after the insertion:
1
,3
,2
. Note: The loop condition in line 12 should bei >= pos - 1
for the correct shifting of elements.