OVERVIEW/REVIEW OF C++ (PART THREE) ====================== do...while loops ---------------- Used to loop ONE or MORE times. do { // statements that get executed at least once, and are repeated // as long as the logical expression evaluates to true. } while ( logical_expression ) ; 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 still executed once, because the expression is not evaluated until the bottom of the loop. Using a loop counter: Counter Controlled Loop For example, count to 10. int count = 1 ; // loop counter variable do { cout << count << endl ; count++ ; // add one to the count variable // same as: count = count + 1 ; // same as: count += 1 ; } while ( count <= 10 ) ; // counter controlled loop Example #2, count down: int count = 10 ; do { cout << "T minus " << count << endl ; count-- ; // subtract one from the count variable // same as: count = count - 1 ; // same as: count -= 1 ; } while ( count > 0 ) ; cout << "We have lift-off!" << endl ; Using a loop exit value: Sentinel Controlled Loop For example, compute the class average: int sum = 0 ; // sum of all grades int count = 0 ; // 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 do { 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++ ; } while ( true ) ; 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 ; }