Help

I want to find the maximum value in a sequence that may have only negative numbers.
With this code I get 0 when I am comparing only negative values...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
using namespace std;

int main ()
{
    int n,number,maximum;
    cin >> n;
    maximum=0;
    for (int cnt=1;cnt<=n;cnt++)
    {
        cin >> number;
        if (maximum<number)
            maximum=number;
    }
    cout << " " << maximum << endl;
    return 0;
}
So, what's wrong? You should get 0 when you are comparing negative values - 0 is higher than any negative number.
Yes that's wrong..Because when I compare negative values I want to get the biggest between them and not 0. :/
1
2
3
4
5
6
7
#include <limits>

...

    int maximum = std::limits<decltype(maximum)>::min() ;

...


Would be one way to do it.
Initialize it to the first value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 #include <iostream>
using namespace std;

int main ()
{
    int n,number,maximum;
    cin >> n;
    cin >> maximum;
    for (int cnt=2;cnt<=n;cnt++)
    {
        cin >> number;
        if (maximum<number)
            maximum=number;
    }
    cout << " " << maximum << endl;
    return 0;
}
Last edited on
closed account (j3Rz8vqX)
I see a lot of good answers, how about this one:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main ()
{
    int n,number,maximum;
    cin >> n;
    maximum=0;
    for (int cnt=1;cnt<=n;cnt++)
    {
        cin >> number;
        if (maximum == 0)
            maximum = number;
        else 
            if (maximum<number)
            maximum=number;
    }
    cout << " " << maximum << endl;
    return 0;
}

I see a lot of good answers, how about this one:


What if the maximum should be 0?
closed account (j3Rz8vqX)
>_< good one, how about this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main ()
{
    int n,number,maximum;
    cin >> n;
    for (int cnt=1;cnt<=n;cnt++)
    {
        cin >> number;
        if (cnt == 1)
            maximum = number;
        else 
            if (maximum<number)
            maximum=number;
    }
    cout << " " << maximum << endl;
    return 0;
}

Sorry binf, I didn't read carefully enough, but guys above explained everything.
Topic archived. No new replies allowed.