How to call this function in main() in cpp

I am trying to use the following remove() function in the main() function. Please let me know what is wrong with my current code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
float remove(float a[], int& n, int i);
int main() {
    float a[]={56.8, 14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1};
    int size, del;
    size =sizeof(a)/sizeof(a[0]);
    cout<<"Enter the element to be deleted!";
    cin >>del;
    cout << "Removed= "<< remove(a, size, del) << "\n";
}

float remove(float a[], int& n, int i){
    for (int j=i+1; j<n; j++)
        a[j-1] = a[j];
     --n;
    }
Last edited on
The function remove doesn't return anything. So what is this meant to do:

<< remove(a, size, del)

Given that the function remove doesn't return anything, what are you passing to << to be output? It makes no sense.
Sorry, I updated the code.
Now your remove function claims to return a float, but it doesn't.

1
2
3
4
5
float remove(float a[], int& n, int i){
    for (int j=i+1; j<n; j++)
        a[j-1] = a[j];
     --n;
    }


Where's the returned float? Nowhere.
That is right, so I should add a return at the end?

1
2
3
4
5
6
float remove(float a[], int& n, int i){
    for (int j=i+1; j<n; j++)
        a[j-1] = a[j];
     --n;
return i;
    }
Last edited on
But the code does not work correctly. When I enter 3, for instance, it outputs 3.

That's what you told it to do.

1
2
3
4
5
6
7
float remove(float a[], int& n, int i)
{
    for (int j=i+1; j<n; j++)
        a[j-1] = a[j];
     --n;
return i;
    }


You told it to return the value of i.

What are you trying to output? What do you want to see on your screen?
I want to be have the removed element displayed on the screen. I mean if I, for instance, enter 3, I want to have 22.3 displayed.
If you'd named your parameters with meaningful names, this would have been an awful lot clearer from the start.
1
2
3
4
5
6
7
8
9
10
11
float remove(float* array, int& size_of_array, int element_to_remove)
{
    float value_to_remove = array[element_to_remove];

    for (int j=element_to_remove; j< size_of_array; j++)
    {
        array[j-1] = array[j];
    }
    size_of_array--;
    return value_to_remove;
}


The actual last value in the array will still be there. So if you went to remove the first value, the array would look like this afterwards:

14.2, 0.2, 22.3, 3.3, 54.02, 543.33, 456,333, 1.1, 1.1

But if you now treat the array as being of size 9, that's not something you have to worry about.

Last edited on
Topic archived. No new replies allowed.