Kapil Arora
Kapil Arora

Reputation: 1

if an array is -5 4 1 , how to remove the negative sign of 5 and make it a complete non-negative array as 5 4 1

    #include<iostream>
    using namespace std;
    int main()
    {
        signed int ar[3]={-5,4,1};
        unsigned ar[0]=5;
        cout<<ar[0];
        return 0;

    }

I have to do in such a way that the resultant array is in descending order so that maximum element would be 5 so 5 will be on top , the above code gives me an error, can anyone please help me to know how or in what manner should I do this?

Upvotes: 1

Views: 336

Answers (2)

user3697569
user3697569

Reputation:

You have to multiply all non-positive numbers by -1, and then use a sorting algorithm to get the array ordered.

Upvotes: 1

Ideasthete
Ideasthete

Reputation: 1541

If an element in the array is less than zero, multiply it by -1. Don't turn it into an unsigned number, that's probably not going to do what you think it does. Also, as mentioned, what you are doing in your code snippet isn't even modifying the element in the array, it's trying to declare a new array. So basically you should do:

if arr[element] < 0 {
    arr[element] *= -1;
}

Upvotes: 1

Related Questions