Write a C program to delete an element at the desired position from an array.

28 Dec 2022 Balmiki Mandal 0 C Programming

C Program to Delete an Element from an Array at a Desired Position

A C program to delete an element at the desired position from an array is a program that takes an array, its size, and a desired position as inputs from the user, and deletes the element at the desired position from the array.

The program needs to check whether the desired position is within the bounds of the array, and if so, it needs to shift all the elements to the left of the desired position to fill the gap left by the deleted element.

After deleting the element, the program should print the updated array to the console. If the desired position is out of bounds, the program should print an error message and not modify the array.

Here is an example C program that deletes an element at a desired position from an array:

C program to delete an element at the desired position from an array

#include<stdio.h>

#define MAX_SIZE 100 // Maximum array size

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

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

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

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

    // Check if position is valid
    if (pos < 1 || pos > size) {
        printf("Invalid position!\n");
    } else {
        // Shift elements to the left
        for (i = pos; i < size; i++) {
            arr[i - 1] = arr[i];
        }

        // Decrement size of the array
        size--;

        // Print the updated array
        printf("Array after deleting element at position %d:\n", pos);
        for (i = 0; i < size; i++) {
            printf("%d ", arr[i]);
        }
        printf("\n");
    }

    return 0;
}

Enter the size of the array: 10

Enter the array elements: 10  10  20  30  40  50  60  70  80  90

Enter the position to delete: 2

Array after deleting element at position 2:  10 20 30 40 50 60 70 80 90

In this program, the user inputs the size and elements of an array, as well as the position to delete. The program then checks if the position is valid (i.e. between 1 and size), shifts all elements to the left starting from the position to delete, decrements the size of the array, and prints the updated array. If the position is not valid, the program prints an error message.

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.