[cs13001] Can't understand this for loop's logic

Mikhail Nesterenko mikhail at cs.kent.edu
Tue Oct 2 16:31:31 EDT 2012


> What I wanted to understand was this issue:
> 
> 1- In a for loop in the program the loop is as follows:


> 
> int i, score[5], max;
> 
> cout << "Enter the score of 5 students: " << endl;
> cin >> score[0];
> max = score[0];
> for (i = 1; i < 5; i++)
> {
>       cin >> score[i];
>       if (score[i] > max) { max = score[i]; }
> }
> 
> I'm supposed to input 5 scores, but doesn't this mean only 4 inputs will be inserted. 1, 2, 3, and 4, because  i   isn't gonna be equal to 5.
> 
> My only guess is, score[0] is already input, so all we need is to input the other 4. Am I right here? Or is there another explanation to this?
> 

The above program is using the classic idiom of searching for a value
in an array (we went over this program in class). In this case, the
program is looking for a maximum. Before the loop, the maximum is
assigned the value of the first element of the array -- score[0].
Then the for-loop iterates over the remaining four elements. Notice
how the loop variable starts from the second index (the second index
is 1). So, in the first iteration, if the second element of the array
score[1] is greater than "max" (which holds the value of the first
element of the array), then "max" is updated. Otherwise, the third
element of the array -- score[2] is examined. This continues for four
iterations.

Thanks,
--
Mikhail


More information about the cs13001 mailing list