OVERVIEW/REVIEW OF C++ (PART FOUR) ====================== for loops --------- Usually used with a self-contained loop counter, but can be used as a generic loop. for ( counter_initialization ; logical_expression ; counter_update ) { // statements that get executed as long as the logical expression // evaluates to true. } As soon as the logical expression evaluates to false, the loop stops looping (and sequence goes to the first statement after the while statement.) If the logical expression evaluates to false the FIRST time, the statements are skipped, and execution proceeds to below the right brace. Using a loop counter: Counter Controlled Loop For example, count to 10. for ( int count = 1 ; count < 11 ; count++ ) // loop counter variable { cout << count << endl ; } Example #2, count down: for ( int count = 10 ; count > 0 ; count-- ) { cout << "T minus " << count << endl ; } cout << "We have lift-off!" << endl ; Using a loop exit value: Sentinel Controlled Loop For example, compute the class average: int sum ; // sum of all grades int count ; // number of grades entered const int SENTINEL = 999 ; // loop end value // NOTE: The sentinel value must be outside the range of normal // data. If this is not possible, then you must use alternate // means (enter data as strings or use end-of-file signals). int number ; // single grade // NOTE: count and sum are initialized here, but cannot be declared // here, because they are still required after the for loop has // completed for ( count = sum = 0 ; ; ) { cout << "Enter a grade from 0 to 100, 999 to stop: " ; cin >> number ; if ( number == SENTINEL ) { break ; // exit the loop } if ( ( number < 0 ) || ( number > 100 ) ) // input validation { cout << number << " is an invalid grade!" << endl ; continue ; // re-start the loop from the top } sum += number ; // same as: sum = sum + number ; count++ ; } if ( count > 0 ) // prevent division by zero { int average = sum / count ; cout << "Class average is " << average << " (from " << count << " grades)" << endl ; } else { cout << "No grades entered." << endl ; }