If forced to put it into words we might describe the process like this:
Start at the first element While we're not at the end of the list If this is the one we're looking for stop searching Otherwise move on to the next
i = 0 ; while( i < num_stud ) if( grades[i][0] > 90 ) break ; ++i ; }
Start at the first element While we're not at the end and we haven't found what we're looking for: Move on to the next element and repeat
i = 0 ; while( i < num_stud && grades[i][0] <= 90 ) ++i ;
for
statement.
Building on this observation, we could code this as:
for( i = 0; i < num_stud && grades[i][0] <= 90; ++i ) ;
for()
part.
(Many recommend some stylistic convention to make it clear that
such an empty body was intentional.
For example some put the comment /* empty */
before the semicolon.
Others put the semicolon on a line by itself.
Some even do both.)
The gist of this statement is that we aren't repeating anything
for each student per se.
Instead, we are interested in this statement for it's side effect:
making i
be the index of the first student that scored over 90.
After we're finished with the loop, we need to ask if we really found it or not. We could follow the loop with something like:
if( i >= num_stud ) { /* error condition */ } else { /* process the student we found */ }
(We sometimes see code where this test is placed inside the loop itself. For example:
for( i = 0; i < num_stud; ++i ) { if( grades[i][0] > 90 ) { /* process the student we found */ break ; } }
if
many times.
If on the other hand, we wanted to do something to each of the
students that scored over 90 (instead of just the first), then
we would use this style.)
Another common searching task is typified by this code that looks for the student who did the best on the first assignment.
best = 0 ; for( i = 1; i < num_stud; ++i ) if( grades[i][0] > grades[best][0] ) best = i ; printf( "Student %d did the best.\n", best ) ;
best
is the number of the student
that has done the best out of all those we've look at so far.
for
statement in the one-line style that
searches for the first student to receive a failing grade (< 60)
on the last assignment (assuming 6 assignments).
Use the variable i
to count through the students.