Program : Remove all occurrences of a specific element from 1-D array in C++.
Solution :
#include <iostream> using namespace std; void removeElement(int array[], int& size, int target) { int index = 0, ; for (i = 0; i < size; i++) { if (array[i] != target) { array[index++] = array[i]; } } size = index; } void printArray(const int array[], int size) { int i; for (i = 0; i < size; i++) { cout << array[i] << " "; } } int main() { const int MAX_SIZE = 100; int size, i, target; int arr[MAX_SIZE]; cout << "Enter the size of the array: "; cin >> size; cout << "Enter the elements of the array: "; for (i = 0; i < size; i++) { cin >> arr[i]; } cout << "Enter the element to remove: "; cin >> target; removeElement(arr, size, target); cout << "Array after removing " << target << ": "; printArray(arr, size); return 0; }
Output :
Enter the size of the array: 8 Enter the elements of the array: 1 2 3 2 4 2 5 2 Enter the element to remove: 2 Array after removing 2: 1 3 4 5
Dry Run :
Let’s walk through the code written inside the removeElement() function with the following inputs:
- Array: [1, 2, 3, 2, 4, 2, 5, 2]
- Element to remove: 2
i | i<size | array[i] | target | Match? | index | array | i++ |
0 | True | 1 | 2 | No | 0 | 1 2 3 2 4 2 5 2 | 1 |
1 | True | 2 | 2 | Yes | – | ——- | 2 |
2 | True | 3 | 2 | No | 1 | 1 3 3 2 4 2 5 2 | 3 |
3 | True | 2 | 2 | Yes | – | ——– | 4 |
4 | True | 4 | 2 | No | 2 | 1 3 4 2 4 2 5 2 | 5 |
5 | True | 2 | 2 | Yes | – | ——— | 6 |
6 | True | 5 | 2 | No | 3 | 1 3 4 5 4 2 5 2 | 7 |
7 | True | 2 | 2 | Yes | – | ———- | 8 |
8 | False | —— | —– | —– | —- | ———- | —- |
Now, after this loop, set the “size” value to “index” value, so that when you want to display the original array then you traverse it till the index.
When you retrieve until the index, then you will find this output : 1 3 4 5.
Want to practice more problems involving Array 1-D ? Click here.