C Program to Remove All Occurrences of an Element in an Array
Last Updated :
02 Aug, 2022
To remove all the occurrences of an element in an array, we will use the following 2 approaches:
- Using Methods
- Without using methods or With Conditional Statement
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input:
array = {1, 2, 1, 3, 1}
value = 1
Output:
array = {2, 3}
Explanation: The given value 1 is to be removed from the array of elements. So, the resultant array is {2, 3} after removing the 1 from an array.
Method 1: Using functions
Approach A:
C
#include <stdio.h>
int remove_element( int * array, int n, int val)
{
int i;
for (i = 0; i < n; i++)
if (array[i] != val)
printf ( "%d " , array[i]);
}
int main()
{
int array[6] = { 1, 2, 1, 3, 1 }, size = 5, value = 1;
remove_element(array, size, value);
}
|
Approach B:
C
#include <stdio.h>
int remove_element( int * array, int n, int val)
{
int i;
for (i = 0; i < n; i++) {
if (array[i] == val) {
continue ;
}
else {
printf ( "%d " , array[i]);
}
}
}
int main()
{
int array[6] = { 1, 2, 1, 3, 1 }, size = 5, value = 1;
remove_element(array, size, value);
return 0;
}
|
Method 2: Without using functions
Approach A:
C
#include <stdio.h>
int main()
{
int array[6] = { 1, 2, 1, 3, 1 }, size = 5, value = 1;
int i;
for (i = 0; i < size; i++) {
if (array[i] == value) {
continue ;
}
else {
printf ( "%d " , array[i]);
}
}
}
|
Approach B:
C
#include <stdio.h>
int main()
{
int array[6] = { 1, 2, 1, 3, 1 }, size = 5, value = 1;
int i;
for (i = 0; i < size; i++) {
if (array[i] != value) {
printf ( "%d " , array[i]);
}
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...