### Very basic array question - help me understand this code.

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include 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:

 ``12345678910`` ``````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.

 ``12345678`` ``````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.