210 likes | 228 Views
Learn the purpose, syntax, semantics, and styles of for loops and do/while loops. Explore examples and variations to improve your loop programming skills.
E N D
for loops Purpose: Improved syntax for Counter-Controlled Loops
for loops c = start; // could be many lines while (c <= stop) { // could be many lines c += increment; }
for loops Syntax: for(initStmt;condExpr;incStmt) body Where: - body is a single statement with a semicolon, or a Block { } .
for loops Semantics: for(initStmt;condExpr;incStmt) body 1. Execute initStmt; 2. When condExpris FALSE, skip the body. When condExpris TRUE: Execute the body Execute the incStmt Repeat step 2.
for loops Style: for(initStmt;condExpr;incStmt) oneStatement; for(initStmt;condExpr;incStmt) { }
for loops Example 1: (warning: poor style!) inti; for(i=2; i<=12; i+=2) cout << i << ” ”; cout << ”\ni =” << i; Prints: 2 4 6 8 10 12 i = 14
for loops Example 1: (style corrected) inti; for(i=2; i<=12; i+=2) cout << i << ” ”; cout << ”\ni =” << i; Prints: 2 4 6 8 10 12 i = 14
for loops Example 2: counting backwards for(i=10; i>=1; i--) { cout << i << ” ”; } cout << ”\ni =” << i; Prints: 10 9 8 7 6 5 4 3 2 1 i = 0
for loops Example 3: zero iterations for(i=10; i<=5; i++) { cout << i << ” ”; } cout << ”\ni =” << i; Prints: i = 10
for loops Example 4: sum all numbers 2 to 10 inti, sum = 0; for(i=2; i<=10; i++) { sum = sum + i; } cout << sum; Prints: 54
for loops Alternate Control Variable Declaration: inti; for(i=1; i<=10; i++) { } Can be written as: for(inti=1; i<=10; i++) { } // but i is undefined after the loop
for loops Nested for loops: Prints: for (inti=1; i<=3; i++) 1 5 for (int j=5; j<=7; j++) 1 6 cout << i << ” ” 1 7 << j << endl; 2 5 2 6 2 7 3 5 3 6 3 7
do/while loops Purpose: Same as a while loop, except the condition is checked at the bottom instead of the top. Use when: there should be at lease one iteration.
do/while loops Syntax: do body while (condExpr); Where: - body is a single statement with a semicolon, or a Block { } .
do/while loops Semantics: do body while (condExpr); 1. Execute thebody 2. When thecondExpris TRUE, repeat step 1 When thecondExpris FALSE, skip body
do/while loops Style 1: do oneStatement; while (condExpr);
do/while loops Style 2: common do { statements } while (condExpr);
do/while loops Style 3: less common do { oneStatement; } while (condExpr);
do/while loops Example 1: validation loop int n; do { cout << ”Enter negative number: ”; cin >> n; if (n >= 0) cout << ”Try again!\n”; } while (n >= 0);
do/while loops Example 2: menu loop string option; do { // print menu, with X=exit cout << ”Enter menu option: ”; cin >> option; // switch or nested if/else’s } while (option != ”X”);