C++

Chapter 5: Loops - Automating Repetition with for, while, and do-while

By Ali Naqi β€’ November 04, 2025

Chapter 5: Loops - Automating Repetition with for, while, and do-while

C++ Tutorial Series - Chapter 5: Loops - Automating Repetition with for, while, and do-while πŸ”

If Chapter 4 gave your code the power to choose, Chapter 5 gives it the power to persevere. Imagine needing to process 1,000 user records, draw 60 frames per second for a game, or keep asking a user for input until they type "quit." Rewriting that code block 1,000 times is impossible. Loops are the solution. They are the final, essential element of core control flow, enabling your C++ program to automate repetitive tasks with incredible efficiency.

1. The Power of Repetition: When to Use Loops

Loops are necessary whenever you need to execute the same set of instructions multiple times. The key is understanding which loop fits the job best:

  • for loop: Best when you know the exact number of times the loop must run (e.g., iterate 10 times, draw 5 items).
  • while loop: Best when the loop needs to run for an indeterminate amount of timeβ€”until a specific, external condition is met (e.g., keep running until user input equals "exit").
  • do-while loop: Best when you need the loop to execute at least once, regardless of the initial condition (e.g., presenting a menu to a user for the first time).

2. The for Loop: The Iteration Specialist

The for loop is compact and perfect for structured iteration. It combines all three control aspects necessary for a counting loop into a single line.

The Three Essential Components

The parentheses hold three distinct expressions, separated by semicolons:


for (initialization; condition; update) {
    // Code block executes here
}
    
  1. Initialization: Executed only once at the very start (e.g., int i = 0).
  2. Condition: Checked before every iteration. If it's true, the loop continues. If false, the loop terminates.
  3. Update: Executed after the code block runs on each iteration (e.g., i++).

#include <iostream>

int main() {
    // Print a countdown from 5 to 1
    for (int i = 5; i > 0; i--) {
        std::cout << "T-" << i << std::endl;
    }
    std::cout << "Lift off!" << std::endl;
    return 0;
}
    
Zero-Indexing Note: In C++ (and most programming languages), we often start counting from 0 (zero-indexing). A common loop to run 10 times is: for (int i = 0; i < 10; i++).

3. The while Loop: The Sentinel Controller

The while loop is the most versatile loop, used primarily when the number of iterations is unknown. It requires you to manage the counter or condition variable explicitly within the loop body.

The Danger of the Infinite Loop

Because the condition is checked at the start, you MUST ensure that the code inside the loop will eventually cause the condition to become false. If not, you create an infinite loop, and your program will hang forever.


#include <iostream>

int main() {
    char input = 'y'; 
    // This loop continues as long as 'input' is 'y' or 'Y'
    while (input == 'y' || input == 'Y') {
        std::cout << "Game continues... (Enter 'n' to stop): ";
        std::cin >> input; // The critical update that prevents the infinite loop!
    }
    std::cout << "Game Over." << std::endl;
    return 0;
}
    

4. The do-while Loop: Guaranteed Execution

The do-while loop is a close cousin to the while loop, but its condition check is at the bottom. The code inside the do { ... } block will always execute at least once before the while (condition); check is performed.

Primary Use Case: Menus and Validation

This structure is perfect for presenting a menu to a user where you need to show the menu once, then check if their input was valid. If the input was invalid, you loop back and show the menu again.


#include <iostream>

int main() {
    int choice;
    do {
        std::cout << "\n--- Main Menu ---\n";
        std::cout << "1. Start Game\n";
        std::cout << "2. Options\n";
        std::cout << "3. Exit\n";
        std::cout << "Enter choice (1-3): ";
        std::cin >> choice;

    } while (choice < 1 || choice > 3); // Loop continues if input is NOT between 1 and 3

    std::cout << "You selected option " << choice << "." << std::endl;
    return 0;
}
    

5. Advanced Loop Control: break and continue

Sometimes you need to fine-tune the execution inside a loop based on a mid-loop condition. These two keywords give you precise control over iteration.

  • break: The "Emergency Exit." It immediately terminates the innermost loop (or switch statement) and forces execution to resume at the statement following the loop body.
  • continue: The "Skip to Next." It immediately stops the current iteration, skips any remaining code in the loop body, and forces the program to jump to the update step (for a for loop) or the condition check (for a while/do-while loop).

#include <iostream>

int main() {
    std::cout << "Numbers 1-10, skipping 5, stopping at 8:" << std::endl;
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            continue; // Skip the rest of the loop for this iteration (don't print 5)
        }
        if (i > 8) {
            break; // Exit the entire loop immediately
        }
        std::cout << i << " ";
    }
    // Output: 1 2 3 4 6 7 8 
    return 0;
}
    

6. Nested Loops: Working in Two Dimensions

A nested loop is a loop placed inside the body of another loop. This is necessary when you need to process data in a two-dimensional structure, like rows and columns in a spreadsheet, or coordinates on a game board. The inner loop executes completely for every single iteration of the outer loop.

The Multiplication Table Example


#include <iostream>

int main() {
    const int SIZE = 5;

    // Outer loop: controls the rows (i)
    for (int i = 1; i <= SIZE; i++) {
        
        // Inner loop: controls the columns (j)
        for (int j = 1; j <= SIZE; j++) {
            // Print the product, formatted with tabs (\t)
            std::cout << i * j << "\t";
        }
        
        // After the inner loop finishes a row, print a newline for the next row
        std::cout << std::endl; 
    }
    return 0;
}
/* Expected Output (First 5x5 Grid):
1    2    3    4    5    
2    4    6    8    10   
3    6    9    12   15   
4    8    12   16   20   
5    10   15   20   25
*/
    

Understanding nested loops is crucial for advanced topics like multi-dimensional arrays (Chapter 7) and game development graphics.


Chapter 5 Conclusion and Next Steps

You have now completed the entire fundamental control flow section of C++! You can store data, make decisions, and automate complex repetition. These first five chapters form the bedrock of all C++ programming.

In Chapter 6, we will move into Functions. Functions are the key to modular programming, allowing you to break down those long programs into manageable, reusable, and testable chunks. This is where your code starts looking professional!