Program to Insert an Element in an Array in Data Structures using C | Insertion Operation


In this article, we will learn how to insert an element in an array in data structures using c. This can be done by the insertion operation to the data structures.

Insertion Operation
In data structures, it simply refers to the addition of a new element to the existing data structures at the specific location. This is called the insertion operation.

C Program

#include <stdio.h>

void main()
{
    int arr[100], size, i, pos, item;

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

    // Ensure size is valid
    if (size <= 0 || size > 100)
    {
        printf("Invalid array size!");
        return;
    }

    printf("Enter the array elements:\n");
    for (i = 0; i < size; i++)
    {
        scanf("%d", &arr[i]);
    }

    printf("Enter the position where you want to insert a new item: ");
    scanf("%d", &pos);

    // Ensure position is valid
    if (pos < 1 || pos > size)
    {
        printf("Invalid position!");
        return;
    }

    printf("Enter the new item that you want to insert: ");
    scanf("%d", &item);

    // Shift elements to the right
    for (i = size; i > pos - 1; i--)
    {
        arr[i] = arr[i - 1];
    }

    // Insert new item
    arr[pos - 1] = item;
    size++;

    printf("The new array elements are: ");
    for (i = 0; i < size; i++)
    {
        printf("%d ", arr[i]);
    }
}


Output:
Enter the size of an array: 5
Enter the array elements:
2
6
8
9
4
Enter the position where you want to insert a new item: 3
Enter the new item that you want to insert: 25
The new array elements are: 2 6 25 8 9 4 

Comments