How to use functions In C Language
Approach A:
C
// C Program to remove All Occurrences of // an element in an array using functions #include <stdio.h> // function declaration int remove_element( int * array, int n, int val) { int i; // iterates array elements for (i = 0; i < n; i++) // if the given array element is not equal to given // value then print array element 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); } |
Output
2 3
Approach B:
C
// C Program to remove all Occurrences of // an element in an array using functions #include <stdio.h> // function declaration int remove_element( int * array, int n, int val) { int i; // iterating the array elements for (i = 0; i < n; i++) { // if array element is equal to the given value then // continue the loop else return the array element 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; } |
Output
2 3
C Program to Remove All Occurrences of an Element in an Array
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.