C Program To Insert An Element In An Array

C Program To Insert An Element In An Array – A simple c program to insert an element at specific location 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]);
    }
}

Explanation: In this program we are traversing in reverse order till we get the index where we want to insert. Also we are shifting the element to the right side. When the loop breaks, the index value will get updated.

Make sure to allocate extra amount of memory when inserting an element in an array.