01 / 21

For, While &
Do-While Loops

Master the three fundamental loop structures in C++ to repeat code efficiently, iterate over data, and control program flow.

C++

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.

Start Condition true? Yes Execute No End

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:

Iteration
Processing each element in an array, string, or collection one at a time.
Automation
Repeating calculations, reading input, or retrying operations until a goal is met.
Algorithms
Searching, sorting, and computing sums all depend on controlled repetition.

C++ Has Three Loop Types

for
Best when you know in advance how many times to repeat. Init, condition, and update all in one line.
while
Best when you don't know how many times to repeat. Checks the condition before each iteration.
do-while
Just like while, but checks condition after each iteration. The body always runs at least once.

The for Loop: Syntax

for (int i = 0; i < 5; i++) {
    cout << "i = " << i << endl;
}
Initialization int i = 0 Condition i < 5 Update i++ Runs in order: init once, then (check condition, run body, update) repeatedly

The while Loop: Syntax

int i = 0;          // initialization
while (i < 5) {    // condition
    cout << i << " ";
    i++;              // update
}

The do-while Loop: Syntax

int choice;
do {
    cout << "Enter 1-3: ";
    cin >> choice;
} while (choice < 1 || choice > 3);
Execute Body Condition true? Yes No Exit

Pre-test vs Post-test Loops

Pre-test (for, while)
Condition is evaluated before the body. If false initially, the body runs zero times.
Post-test (do-while)
Condition is evaluated after the body. The body always runs at least once, even if the condition is false.
// Pre-test: body may never run
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

1
Do you know the count? If the number of iterations is known (e.g., iterate \( n \) times), use a for loop.
2
Unknown count, but might be zero? If the loop might not need to run at all, use a while loop.
3
Must run at least once? If the body must execute before checking (input validation, menus), use a do-while loop.
4
Ensure the loop terminates. Verify that the condition will eventually become false: the update step must bring the loop closer to its exit condition.

Example: Sum of \( 1 \) to \( n \)

int n = 5, sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}
cout << sum;  // Output: 15
Iteration trace: i sum before sum after 1 0 1 2 1 3 3 3 6 ... i=5 sum = 15

Example: while Loop with User Input

int num;
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

int choice;
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 row = 1; row <= 3; row++) {
    for (int col = 1; col <= 4; col++) {
        cout << "* ";
    }
    cout << endl;
}

break and continue

break
Immediately exits the loop entirely. Execution jumps to the first statement after the loop.
continue
Skips the rest of the current iteration and jumps back to the loop's condition check (or update in a for loop).
for (int i = 1; i <= 10; i++) {
    if (i == 6) break;     // stops at 6
    if (i % 2 == 0) continue; // skip evens
    cout << i << " ";
}
// Output: 1 3 5

Common Mistakes

✕ Infinite Loop
Forgetting the update step (e.g., missing i++) so the condition never becomes false. The program hangs forever.
✕ Off-by-One Error
Using < when you need <= (or vice versa). This causes the loop to run one too many or one too few times.
✕ Semicolon After for
Writing 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++; }