Why is the output 9?

Can someone please explain the steps involved to determine that the output of this code is 9? I'm reviewing for a final and none of the lesson readings or labs are helping. Thanks.

int arr[5] = {2, 6, 5, 7, 9};
int la = arr[0];
for (int c = 1; c < 5; c = c + 1)
{
if (arr[c] > la)
{
la = arr[c];
}
}
cout << la << endl;
la = 2;
1. Declarations
2. c = 1. // Loop starts here
3. Check if c is less then 5(it is)//checking loop condition
4. is arr[c] less then la? // arr[1] = 6, la = 2; it is
5. la is now 6.
6. add 1 to c // (iteration)
7. check if c i less then 5 // (2 is less then 5). It is loop condition again.
...
last: show result.

What you have here, is the function that goes through whole array and finds highest number in the array.
It can be rewritten (so you can read code like it was in English) to:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define ArraySize 5 // array size is five.
int ArrayOfNumbers[ArraySize] = { 2, 6, 5, 7, 9};
int HighestNumber = arr[0];//We start by setting first number from array as the highest one... for now
for(int CurrentPositionInArray = 1; CurrentPositionInArray < ArraySize; CurrentPositionInArray++)
{

//if current number in array is higher then our highest number
 if(ArrayOfNumbers[CurrentPositionInArray] > HighestNumber)
 {
   // make it our highest number
   HighestNumber = ArrayOfNumbers[CurrentPositionInArray];
 }
 cout<< HighestNumber << endl;
}


Hope it helped.
Cheers!
Last edited on
Thanks for your help! Once I realized the purpose of the loop things were easier to understand. Again, thank you very much for responding.
Topic archived. No new replies allowed.