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
deleteElementthat 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
mainfunction, we take input from the user for the position from which the element should be deleted, and then call thedeleteElementfunction. - We print the updated array after deletion.