Repetition Statements The question being asked is "Should I execute the statement block AGAIN?" All repetition statements use a boolean expression to make the decision. 3 Repetition statements while for do / while "while" is the general all-purpose looper. The other two are special purpose.
while( boolean expression ) statement; { statement1; statement2; statement3; } int counter = 1; . while( counter < 10 ) cout << "My name is Lee." << endl; counter++; { }
cout << "Enter a value below 100 to start with: "; double start; cout << "Enter a value below 100 to start with: "; cin >> start; while( start < 100 ) start *= 1.1; cout << "The final value of start is: " << start << endl; How many times is the loop going to execute? Don't know, it depends on the starting value. BUDDY SAGA. loopcount.cpp loopcount1.cpp loopflag.cpp loopsentinel.cpp NEXT: LoopBADSentinel.cpp
#include <iostream.h> int main() { double sqMeters = 1, //Input by user sqYards; //Calculated while( sqMeters != 0 ) cout << "Enter number of square meters: "; cin >> sqMeters; //Apply the conversion factor and report. sqYards = sqMeters * 1.196; cout << "Number of square yards: " << sqYards << endl; } return 0; Next – "for" loop
for( initialization ; boolean expression ; incrementing action ) statement block; int counter; for( counter = 0; counter < 10; counter++ ) cout << "This is line number " << counter + 1 << endl; int reps, total; for (reps = 0; reps <= 6; reps++) { total = reps * 8; cout << total << endl; } Counter control only
while( <boolean expression> ); do statement; while( <boolean expression> ); do { statement1; statement2; . statementn; } while( <boolean expression> ); When the code in the statement block MUST execute at least one time.
int count = 0; do { cout << "Count: " << count << " " << count * count << endl; count++; } while( count < 20 ); int count = 0; do cout << "This is line " << ++count << endl; while( count < 20 );
Selecting the Correct Repetition Statement if( the statement block must execute at least one time ) Select the do/while else if( it's pure counter-control ) Select the for else //for anything else Select the while