C program to insert an element in an array

To insert an element in an array in C, you can follow these steps:

  1. Declare a one-dimensional array of some fixed capacity.
  2. Take the size of the array as input from the user.
  3. Define array elements, taking each element as input from the user.
  4. Get the number to be inserted.
  5. Get the position where the element needs to be inserted.
  6. Shift all elements to one position forward from the specified position.
  7. 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:

  1. The program prompts the user to enter two integers into an array (assuming for loop should run for i < 3 to match array size).
  2. It then takes user input for the element (3) and the index (1) at which the user wants to insert a new element.
  3. Using a loop, it shifts elements to the right starting from the specified index to make space for the new element.
  4. It inserts the user-specified element at the specified index in the array.
  5. The final array is printed, showing the result after the insertion: 1, 3, 2. Note: The loop condition in line 12 should be i >= pos - 1 for the correct shifting of elements.

Leave a Comment