For, While &
Do-While Loops
Master the three fundamental loop structures in C++ to repeat code efficiently, iterate over data, and control program flow.
What Is a Loop?
A loop is a control structure that repeats a block of code as long as a specified condition remains true. Instead of writing the same lines over and over, loops let you express repetition in a single, compact structure.
Why Loops Matter
Without loops, printing numbers from \(1\) to \(1000\) would require 1000 separate statements. Loops compress that into just a few lines. They are essential for:
C++ Has Three Loop Types
The for Loop: Syntax
cout << "i = " << i << endl;
}
The while Loop: Syntax
while (i < 5) { // condition
cout << i << " ";
i++; // update
}
The do-while Loop: Syntax
do {
cout << "Enter 1-3: ";
cin >> choice;
} while (choice < 1 || choice > 3);
Pre-test vs Post-test Loops
int x = 10;
while (x < 5) { cout << x; } // prints nothing
// Post-test: body runs once
int y = 10;
do { cout << y; } while (y < 5); // prints 10
How to Choose the Right Loop
Example: Sum of \( 1 \) to \( n \)
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << sum; // Output: 15
Example: while Loop with User Input
cout << "Enter a positive number (0 to stop): ";
cin >> num;
while (num != 0) {
cout << "You entered: " << num << endl;
cin >> num;
}
cout << "Done!";
Example: do-while Menu Validation
do {
cout << "Menu:\n";
cout << "1. Play\n2. Settings\n3. Quit\n";
cout << "Choose 1-3: ";
cin >> choice;
} while (choice < 1 || choice > 3);
Nested Loops
A loop placed inside another loop creates a nested loop. The inner loop completes all its iterations for each single iteration of the outer loop.
for (int col = 1; col <= 4; col++) {
cout << "* ";
}
cout << endl;
}
break and continue
if (i == 6) break; // stops at 6
if (i % 2 == 0) continue; // skip evens
cout << i << " ";
}
// Output: 1 3 5
Common Mistakes
i++) so the condition never becomes false. The program hangs forever.< when you need <= (or vice versa). This causes the loop to run one too many or one too few times.for(...); with a semicolon creates an empty loop body. The intended body runs only once, after the loop finishes.Loop Comparison Table
| Feature | for | while | do-while |
|---|---|---|---|
| Condition check | Before body | Before body | After body |
| Min executions | \(0\) | \(0\) | \(1\) |
| Init in header? | Yes | No | No |
| Update in header? | Yes | No | No |
| Best for | Known count | Unknown count | Run-at-least-once |
| Ends with | } |
} |
}; (semicolon!) |
Question 1 of 5
What is the output of the following code?for (int i = 0; i < 3; i++) { cout << i << " "; }
Question 2 of 5
Which loop guarantees the body executes at least once?
Question 3 of 5
What happens if you write for (int i = 0; i < 5; i++); with a semicolon after the parentheses?
Question 4 of 5
What does the continue keyword do inside a loop?
Question 5 of 5
How many times does the following loop print "Hello"?int x = 10; while (x < 5) { cout << "Hello"; x++; }