In this tutorial, we will write a C program to delete an element in an array by specifying the value. Before that, you should have knowledge on the following C topics:
Example:
Input
Input array elements: 11 22 30 42 50
Specify the value to delete: 22
Output
Array elements: 11 30 42 50
Explanation: Here instead of a position of an element, the value of the element is specified to delete. Similarly, the program traverse until the element is found and then shifts all the elements from index + 1 by 1 position to the left.
And if the value is not that is the entered value does not match with any element present in an array, in that case, the program will display the message “Element Not Valid”.
C Program to Delete a Particular element from an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | #include <stdio.h> int main() { int arr[50], element, i, size, pos; int element_found = 0; printf("Enter the size of an array: "); scanf("%d", &size); printf("Enter %d elements\n", size); for (i = 0; i < size; i++) scanf("%d", &arr[i]); printf("\nArray before Deletion:\n"); for (i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n\nEnter the element to be deleted: "); scanf("%d", &element); // check the element to be deleted is in array or not for (i = 0; i < size; i++) { if (arr[i] == element) { element_found = 1; pos = i; break; // terminate the loop } } if (element_found == 1) // for element exists { for (i = pos; i < size - 1; i++) arr[i] = arr[i + 1]; } else //for element does not exists printf("\nElement %d is not present in an Array. Try Again!", element); printf("\nArray after Deletion:\n"); for (i = 0; i < size - 1; i++) printf("%d ", arr[i]); return 0; } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Enter the size of an array: 5 Enter 5 elements 10 20 30 40 50 Array before Deletion: 10 20 30 40 50 Enter the element to be deleted: 30 Array after Deletion: 10 20 40 50 |