Topic-31:Deletion in Array

Deletion of an element from an array involves removing an element from a specified position in the array and shifting the subsequent elements to fill the gap.

Example:

#include <stdio.h>

 

#define MAX_SIZE 100

 

void deleteElement(int array[], int *size, int position) {

    // Check if the array is empty

    if (*size == 0) {

        printf(“Array is empty. Deletion failed.\n”);

        return;

    }

 

    // Check if the position is valid

    if (position < 0 || position >= *size) {

        printf(“Invalid position. Deletion failed.\n”);

        return;

    }

 

    // Shift elements to the left starting from the position to be deleted

    for (int i = position; i < *size – 1; i++) {

        array[i] = array[i + 1];

    }

 

    // Decrement the size of the array

    (*size)–;

 

    printf(“Element deleted successfully.\n”);

}

 

int main() {

    int arr[MAX_SIZE] = {1, 2, 3, 4, 5}; // Example array

    int size = 5; // Current size of the array

 

    int position;

 

    printf(“Enter position to delete: “);

    scanf(“%d”, &position);

 

    // Call the deleteElement function to delete the element

    deleteElement(arr, &size, position);

 

    // Print the updated array

    printf(“Updated Array:\n”);

    for (int i = 0; i < size; i++) {

        printf(“%d “, arr[i]);

    }

    printf(“\n”);

 

    return 0;

}

 
 

Explanation:

  • We have a function deleteElement that takes the array, its current size, and the position from which the element needs to be deleted.
  • Inside deleteElement, we first check if the array is empty or if the position is valid. If not, we print an appropriate message and return.
  • Then, we shift elements to the left starting from the specified position to remove the element.
  • After shifting, we decrement the size of the array to reflect the removal of the element.
  • In the main function, we take input from the user for the position from which the element should be deleted, and then call the deleteElement function.
  • We print the updated array after deletion.

Leave a Comment

Your email address will not be published. Required fields are marked *