Program to Delete an Element from an Array in Data Structures using C | Deletion Operation


As we discussed the insertion operation in the previous article, here we will learn how to delete an element from an array in data structures using c. Let's take a look!

Deletion Operation
In data structures, it refers to the process of removing an element from the existing data structures from any random position. This is called a deletion operation. We can perform deletion by using this operation.

C Program

#include <stdio.h>

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

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

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

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

    printf("Enter the position of an element that you want to delete: ");
    scanf("%d", &pos);

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

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

    // Decrease the size after deletion
    size--;

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

    return 0;
}


Output:
Enter the size of an array: 5
Enter the elements in an array:
2
6
9
0
1
Enter the position of an element that you want to delete: 4
The updated array elements are: 2 6 9 1 

Comments