Search code examples
c++arraysfunctionloopsabsolute-value

unable to convert negative values to positive in array?


I need to return true/false if there was any integer converted to positive in an array, I am able to return true or false however I am not able to convert the negative integers into positive?

#include <iostream>
using namespace std;

int convertArray (int a[],int sizeofArray )     

{
bool v = false;
for (int i=0; i<sizeofArray; i++)
{   

    if(a[i]<0)
    {
        abs(a[i]);
        v = true;

    }

  cout << i << "  " << a[i] << endl;  
}
return v;



}
int main()

{
    int b[5] = {1,-2,3,5,2};
    cout << convertArray (b,5)<<endl;

        return 0;
}

Solution

  • The statement:

    abs(a[i]);
    

    does just the conversion but the value is lost since you are not re-assigning to the corresponding array element and the parameter is not passed by reference. You should have:

    a[i] = abs(a[i]);