C Program to Delete an Element from Array

1. Introduction

One of the fundamental operations while working with arrays is the deletion of an element at a specific position. In this post, we will be demonstrating a C program to delete an element from a specified position in an array. We will also provide a step-by-step explanation of the program.

2. Program Overview

The following C program will:

1. Obtain the size of the array and its elements from the user.

2. Request the position of the element the user wants to delete.

3. Delete the element from the specified position.

4. Showcase the modified array to the user.

3. Code Program

#include <stdio.h>

int main() {
    int n, i, pos;
    int arr[100];
    
    // Collecting the number of elements in the array
    printf("Enter the number of elements in array: ");
    scanf("%d", &n);
    
    // Obtaining the elements
    printf("Enter %d integers:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Getting the position of the element to delete
    printf("Enter the position of element to delete (0 to %d): ", n-1);
    scanf("%d", &pos);
    
    // Deleting the element
    for(i = pos; i < n-1; i++) {
        arr[i] = arr[i+1];
    }

    // Displaying the result
    printf("Resultant array is:\n");
    for(i = 0; i < n-1; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

Output:

Enter the number of elements in array: 5
Enter 5 integers:
10
20
30
40
50
Enter the position of element to delete (0 to 4): 4
Resultant array is:
10 20 30 40

4. Step By Step Explanation

1. Variable Declaration:

- n is used to store the number of elements in the array.

- arr[100] represents the array holding our elements.

- pos is the position from which we will delete an element.

2. Input Gathering:

- We start by getting the number of elements and then each individual element from the user.

- Next, we ask the user for the position of the element they wish to delete.

3. Element Deletion:

- To delete the desired element, we shift all the elements from its right, one position to the left. This overwrites the element at the position, essentially deleting it.

- It's important to note that this doesn't free up memory; it only changes the value. If we were using dynamic memory allocation, we would need to free the memory too.

4. Displaying the Modified Array: We then display the new array after deletion.

Through this method, one can delete an element from any position in the array. Nonetheless, it's crucial to be cautious and not try to delete a position outside the range of the array to avoid unexpected results.

Comments