Delete an Element from an Array at Given Position

In C programming, deleting an element from an array means removing the element from a specific position and shifting the remaining elements to the left.

Since arrays in C have a fixed size, the last element is usually ignored after shifting the elements.

1. Problem Statement

Write a C program to delete an element from an array at a given position entered by the user.

After deletion, the program should display the updated array.

2. Algorithm

Step 1: Start the program.

Step 2: Declare an array and variables.

Step 3: Read the number of elements in the array.

Step 4: Input the array elements.

Step 5: Read the position of the element to delete.

Step 6: Shift elements to the left from that position.

Step 7: Reduce the array size by one.

Step 8: Display the updated array.

Step 9: End.

3. C Program

C
Program to delete an element from an array at a given position
#include <stdio.h>

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

    printf("Enter number of elements: ");
    scanf("%d", &n);

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

    printf("Enter the position to delete: ");
    scanf("%d", &pos);

    if(pos < 1 || pos > n) {
        printf("Invalid position!");
    } else {
        for(i = pos - 1; i < n - 1; i++) {
            arr[i] = arr[i + 1];
        }

        n--;

        printf("Array after deletion:\n");
        for(i = 0; i < n; i++) {
            printf("%d ", arr[i]);
        }
    }

    return 0;
}

4. Example

Input:
Enter number of elements: 5
Enter elements: 10 20 30 40 50
Enter the position to delete: 3
Output:
Array after deletion:
10 20 40 50

Notes

Deleting an element from an array requires shifting all elements after the deleted position one place to the left.

Arrays in C have fixed size, so we logically reduce the size after deletion instead of actually shrinking the array.