My max function always goes to the last number

Jun 30, 2015 at 11:37am
Why does my max function (meant to find the highest number within the array of 10 numbers) ALWAYS state the very last number in the array?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <ctime>
#include <limits>

using namespace std;

int main( )
{
   int Input;
   int x;
   int arr[10];

   for (x = 0; x < 10; x++)
   {
       cout << "Enter the # of pancakes person #" << x << " ate:" << endl;
       cin >> Input;

       arr[x] = Input; // This creates an array of 10 numbers I input
   }

   int max = 0;

   cout << " " << endl;

   for (x = 0; x < 10; x++)
   {
       if (max < arr[x]); // This is my (defective) max function
       {
           max = arr[x];
       }

   }
cout << " " << endl;

cout << max << endl;

   return 0;
}


I've also tried editing the code to have:
1
2
3
4
5
for (x = 0; x < 10; x++)
{
     if (max < arr[x]);
     max = arr[x];
}

but the problem still isn't fixed.

For example, if I say person #1 ate 99 pancakes, person #2 - #8 ate 0 pancakes, and person #9 at 2 pancakes, the last statement would say "max = 2" instead of "max = 99."

Last edited on Jun 30, 2015 at 11:38am
Jun 30, 2015 at 12:01pm
27
28
29
30
       if (max < arr[x]); //<-- look at the semicolon
       {
           max = arr[x];
       }
that could be writted as
1
2
3
if (max < arr[x])
	; //<--
max = arr[x];
As you may note by the indentation the max = arr[x]; statement does not form part of the if.
It is executed always on every iteration, and so, `max' would hold the last value of the array.

Simply remove the semicolon at line 27
Last edited on Jun 30, 2015 at 12:01pm
Jun 30, 2015 at 12:06pm
@ne555 DAMN wow.... can't believe I wasted 30min to an hour on that. Thanks so much :D and for everyone else who's replied on my threads
Topic archived. No new replies allowed.