In this tutorial, we are going to learn to write C Program to delete a given element from an array. To delete the given element we will compare the given element with the array elements. If we find a match then will delete the element from the array otherwise will check for the next array element. This process will continue till the end of the array.
Our problem statement
Suppose we have an array that has elements a={1,2,3,4,5}. We want to delete element 3 from the array. So after deleting element 3 from the array, the new array would be a={1,2,4,5}.
Here we are deleting the element from an array, not deleting the elements from the array index.
Our approach to to delete given element from array
- We will take the value in the array
- Now we will compare the element which we want to delete from array with all array elements.
- To iterate array we are using for loop in c and to compare elements we are using equal(==) operator and if statement.
- We have also handled the scenario, suppose if we have element that is repeated multiple times. We will delete the all occurrence as well.
C Program to delete given element from array
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, size, value, j, temp;
printf("=== C Program to Delete Given Element from Array ===\n");
// Taking input for the size of the array
printf("Enter size of the array: ");
scanf("%d", &size);
int arr[size];
temp = size;
// Taking input for array elements
for(i = 0; i < size; i++) {
printf("Please give value for index %d: ", i);
scanf("%d", &arr[i]);
}
// Taking input for the element to delete
printf("Enter the element to delete: ");
scanf("%d", &value);
// Deleting the given element
for(i = 0; i < size; i++) {
if(arr[i] == value) {
for(j = i; j < size - 1; j++) {
arr[j] = arr[j + 1];
}
size--;
i--; // To check if the element occurs more than once
}
}
// If no element was found, print message
if(temp == size) {
printf("No element %d found in the array\n", value);
exit(0);
}
// Displaying the array after deletion
printf("Remaining elements of the array after deleting %d are:\n", value);
for(i = 0; i < size; i++) {
printf("%d\n", arr[i]);
}
return 0;
}
Output
=== C Program to Delete Given Element from Array ===
Enter size of the array: 6
Please give value for index 0: 4
Please give value for index 1: 3
Please give value for index 2: 2
Please give value for index 3: 1
Please give value for index 4: 3
Please give value for index 5: 2
Enter the element to delete: 2
Remaining elements of the array after deleting 2 are:
4
3
1
3
What did you think?