noor ahmad noor ahmad - 1 year ago 99
C++ Question

Removing an element from array without any built-in function in c++

The question is:
"Write and test the following function that removes items from an array:

void removeAll(float a[], int& n, float x);


The function removes all occurrences of x among the first n elements of the array and decreases the value of n by the number removed.

I have written a code and it works perfectly fine. Basically, I tagged the value whose occurrences the user wants to remove with Zero and the code skips printing when it encounters zero. Basically we are not removing that value from the array just replacing it with some other value. What if the user entered zero in the array? then the other zeroes will also be skipped which I don't want them too. how can I do this?

Here is my code:

Don't use any classes, objects, vectors, strings nor any function in c++ which is like array.splice in js.

#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);
}

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download