The question is:
"Write and test the following function that removes items from an array:
void removeAll(float a[], int& n, float x);
#include<iostream>
using namespace std;
void removeAll(float a[], int &n, float x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
a[i] = 0;
}
}
for (int i = 0; i < 10; i++)
{
if (a[i]!=0)
cout << a[i] << endl;
}
}
int main()
{
float a[10], x;
int n;
cout << "Enter values in array: \n";
for (int i = 0; i < 10; i++)
{
cin >> a[i];
}
cout << "Enter the value whose occurrence you want to remove from the array: ";
cin >> x;
cout << "Enter serial no. uptill which you want to remove the occurences";
cin >> n;
removeAll(a, n, x);
}
If you just want to print out the array without a chosen variable you can do it with one condition:
void removeAll(float a[], int &n, float x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
// Don't print it
}
else
{
cout << a[i] << endl;
}
}
}
If you want to eliminate the occurrences I would suggest to move the following numbers forward. I won't code it but here is an example:
array: 2,3,4,5,3,7
number to remove: 3
1. Iterate through the array and find '3'
2. If you find one, move all elements on the right side on step to left:
2 3 4 5 3 7 => 2 4 5 3 7 X
^
2 4 5 3 7 X => 2 4 5 7 X X
^
3. Count how many times you have done step two and return the new length/new array