C program to insert an element in array

Write a C program to insert element in array at specified position. C program to insert element in array at given position. The program should also print an error message if the insert position is invalid. Logic to insert an element in array at given position in C program.

Example

Input

Input array elements: 10, 20, 30, 40, 50
Input element to insert: 25
Input position where to insert: 3

Output

Elements of array are: 10, 20, 25, 30, 40, 50

Required knowledge

Basic Input Output, For loop, Array

Logic to insert element in array

Step by step descriptive logic to insert element in array.

  1. Input size and elements in array. Store it in some variable say size and arr.
  2. Input new element and position to insert in array. Store it in some variable say num and pos.

    Array insertion

  3. To insert new element in array, shift elements from the given insert position to one position right. Hence, run a loop in descending order from size to pos to insert. The loop structure should look like for(i=size; i>=pos; i--).

    Inside the loop copy previous element to current element by arr[i] = arr[i - 1];.

    Read more – C program to copy array element

    Array insertion

  4. Finally, after performing shift operation. Copy the new element at its specified position i.e. arr[pos - 1] = num;.
    Array insertion

Program to insert element in array

/**
 * C program to insert an element in array at specified position
 */

#include <stdio.h>
#define MAX_SIZE 100

int main()
{
    int arr[MAX_SIZE];
    int i, size, num, pos;

    /* Input size of the array */
    printf("Enter size of the array : ");
    scanf("%d", &size);

    /* Input elements in array */
    printf("Enter elements in array : ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    /* Input new element and position to insert */
    printf("Enter element to insert : ");
    scanf("%d", &num);
    printf("Enter the element position : ");
    scanf("%d", &pos);

    /* If position of element is not valid */
    if(pos > size+1 || pos <= 0)
    {
        printf("Invalid position! Please enter position between 1 to %d", size);
    }
    else
    {
        /* Make room for new array element by shifting to right */
        for(i=size; i>=pos; i--)
        {
            arr[i] = arr[i-1];
        }
        
        /* Insert new element at given position and increment size */
        arr[pos-1] = num;
        size++; 

        /* Print array after insert operation */
        printf("Array elements after insertion : ");
        for(i=0; i<size; i++)
        {
            printf("%d\t", arr[i]);
        }
    }

    return 0;
}

Output

Enter size of the array : 5
Enter elements in array : 10 20 30 40 50
Enter element to insert : 25
Enter the element position : 3
Array elements after insertion : 10      20      25      30      40      50

Happy coding 😉