Very basic array question - help me understand this code.

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
#include <iostream>

using namespace std;

int main()
{
    int i;
    int score[5];
    int max;

    cout << "Enter 5 scores: " << endl;
    cin >> score[0];

    max = score[0];

    for (i = 1; i < 5; i++)
    {
        cin >> score[i];
        if (score[i] > max)
        {
            max = score[i];
        }
    }

    cout << "The highest score is: " << max << endl
         << "The scores and their differences from the highest are: " << endl;

    for (i = 0; i < 5; i++)
    {
        cout << score[i] << " off by " << (max - score[i]) << endl;
    }
}


We just got into arrays, and I'm having trouble understanding exactly what these lines are doing:

1
2
3
4
5
6
7
8
9
10
max = score[0];

    for (i = 1; i < 5; i++)
    {
        cin >> score[i];
        if (score[i] > max)
        {
            max = score[i];
        }
    }


I'll take it from the top with how I interpret this. Please help me out along the way:

max = score[0];

Set max equal to the very first number entered.

1
2
3
4
5
6
7
8
for (i = 1; i < 5; i++)
    {
        cin >> score[i];
        if (score[i] > max)
        {
            max = score[i];
        }
    }

The program then keeps looping until you have entered the other 4 numbers, thus why the variable i starts off at 1, and gets incremented until i reaches the last place in the array.

Then, if the any of the numbers entered are bigger than the previous number entered, max becomes that number?

But if what I'm saying is correct, since the very first number entered is not in the loop, how does it know that that first number isn't the biggest? Or is that what max = score[0]; is there for?
Last edited on
But if what I'm saying is correct, since the very first number entered is not in the loop, how does it know that that first number isn't the biggest? Or is that what max = score[0]; is there for?

Yeah, exactly. When the loop starts, max is already equal to the first score in the array, score[0]. If any of the later values are greater than that, max is replaced.
Topic archived. No new replies allowed.