Download presentation
Presentation is loading. Please wait.
1
for & do/while Loops
2
Purpose: Improved syntax for Counter-Controlled Loops
for loops Purpose: Improved syntax for Counter-Controlled Loops
3
for loops c = start; // could be many lines while (c <= stop) { c += increment; }
4
for loops Syntax: for (initStmt; condExpr; incStmt) body Where:
- body is a single statement with a semicolon, or a Block { } .
5
for loops Semantics: for (initStmt; condExpr; incStmt) body
1. Execute initStmt; 2. When condExpr is FALSE, skip the body. When condExpr is TRUE: Execute the body Execute the incStmt Repeat step 2.
6
for loops Style: for (initStmt; condExpr; incStmt) oneStatement ; { }
7
for loops Example 1: (warning: poor style!) int i;
for (i=2; i<=12; i+=2) cout << i << ” ”; cout << ”\ni =” << i; Prints: i = 14
8
for loops Example 1: (style corrected) int i;
for (i=2; i<=12; i+=2) cout << i << ” ”; cout << ”\ni =” << i; Prints: i = 14
9
for loops Example 2: counting backwards for (i=10; i>=1; i--) {
cout << i << ” ”; } cout << ”\ni =” << i; Prints: i = 0
10
for loops Example 3: zero iterations for (i=10; i<=5; i++) {
cout << i << ” ”; } cout << ”\ni =” << i; Prints: i = 10
11
for loops Example 4: sum all numbers 2 to 10 int i, sum = 0;
for (i=2; i<=10; i++) { sum = sum + i; } cout << sum; Prints: 54
12
for loops Alternate Control Variable Declaration: int i; for (i=1; i<=10; i++) { } Can be written as: for (int i=1; i<=10; i++) { // but i is undefined after the loop
13
for loops Nested for loops: Prints: for (int i=1; i<=3; i++) 1 5 for (int j=5; j<=7; j++) 1 6 cout << i << ” ” 1 7 << j << endl;
14
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.
15
do/while loops Syntax: do body while (condExpr); Where:
- body is a single statement with a semicolon, or a Block { } .
16
do/while loops Semantics: do body while (condExpr);
1. Execute the body 2. When the condExpr is TRUE, repeat step 1 When the condExpr is FALSE, skip body
17
do/while loops Style 1: do oneStatement; while (condExpr);
18
do/while loops Style 2: common do { statements } while (condExpr);
19
do/while loops Style 3: less common do { oneStatement; }
while (condExpr);
20
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);
21
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”);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.