Loops in C++: for, while, and do-while

In programming, we often need to perform the same action multiple times. Imagine you need to print “Hello, World!” 100 times. Would you copy and paste the same line of code 100 times? Definitely not! This is where loops come in. Loops are fundamental control structures in C++ that allow you to execute a block of code repeatedly. Mastering the three main types of loopsโ€”for, while, and do-whileโ€”is a giant leap forward for any beginner programmer.

๐Ÿ”น Quick Reference: Which Loop Should You Use?

Loop TypePrimary Use CaseAnalogy
forWhen you know the exact number of iterations.Running a specific number of laps around a track.
whileWhen you want to loop as long as a condition is true, and the number of iterations is unknown.Reading a book until you reach the last page.
do-whileWhen you need the loop to run at least once, regardless of the condition.Pressing the “on” button of an appliance at least once to see if it works.

1. The for Loop: The Counter

The for loop is your go-to choice when you know exactly how many times you want a piece of code to run. It’s compact and bundles the initialization, condition, and update expressions into one line.

#include <iostream>
int main() {
    // This for loop will run 5 times.
    // 1. Initialization: `int i = 1;` runs once at the very beginning.
    // 2. Condition: `i <= 5;` is checked before each iteration.
    // 3. Update: `i++` runs at the end of each iteration.
    for (int i = 1; i <= 5; i++) {
        std::cout << "This is loop iteration number " << i << std::endl;
    }
    
    return 0;
}

Output

This is loop iteration number 1
This is loop iteration number 2
This is loop iteration number 3
This is loop iteration number 4
This is loop iteration number 5

๐Ÿ“ Try it Yourself: Write a for loop that prints all the even numbers from 2 to 20.

2. The while Loop: The Condition Checker

The while loop is perfect for situations where you don’t know the exact number of iterations, but you know the condition that needs to be true for the loop to continue. The condition is checked before each iteration.

#include <iostream>
#include <string>
int main() {
    std::string input = "";
    // The loop continues as long as the user's input is not "quit".
    while (input != "quit") {
        std::cout << "Enter a message (or type 'quit' to exit): ";
        std::getline(std::cin, input);
        
        if (input != "quit") {
            std::cout << "You entered: " << input << std::endl;
        }
    }
    std::cout << "Goodbye!" << std::endl;
    return 0;
}

Output

Enter a message (or type 'quit' to exit): Hello
You entered: Hello
Enter a message (or type 'quit' to exit): C++ is fun
You entered: C++ is fun
Enter a message (or type 'quit' to exit): quit
Goodbye!

๐Ÿ“ Try it Yourself: Create a program with a `while` loop that generates random numbers between 1 and 10 and stops once it generates the number 7.

3. The do-while Loop: The “Do It Once” Loop

The do-while loop is a variation of the while loop. Its unique feature is that it always executes the code block at least once, because the condition is checked after the block runs.

This makes it ideal for situations like displaying a menu to a user, where you want the menu to show up at least one time.

#include <iostream>
int main() {
    int choice;
    // The do-while loop guarantees the menu is displayed at least once.
    do {
        // 1. The code block runs first.
        std::cout << "--- Menu ---" << std::endl;
        std::cout << "1. Start Game" << std::endl;
        std::cout << "2. Load Game" << std::endl;
        std::cout << "3. Quit" << std::endl;
        std::cout << "Enter your choice: ";
        std::cin >> choice;
        // 2. The condition is checked at the end.
        // The loop will repeat as long as the choice is not 3.
    } while (choice != 3);
    std::cout << "Exiting program..." << std::endl;
    return 0;
}

Output

--- Menu ---
1. Start Game
2. Load Game
3. Quit
Enter your choice: 1
--- Menu ---
1. Start Game
2. Load Game
3. Quit
Enter your choice: 3
Exiting program...

๐Ÿ“ Try it Yourself: Write a program using a do-while loop that asks the user to enter a number greater than 10. The loop should continue to prompt them until they enter a valid number.

๐Ÿ”น Frequently Asked Questions (FAQ)

Q: What is an infinite loop and how do I avoid it?
A: An infinite loop is a loop whose condition never becomes false, causing it to run forever. You can avoid it by making sure that the variable in your loop’s condition is updated correctly inside the loop body so that the condition will eventually become false.

Q: Can I put a loop inside another loop?
A: Yes! This is called a nested loop. It’s a common technique used for working with 2D structures like grids or tables. For example, the outer loop could iterate over rows, and the inner loop could iterate over columns.

Q: How can I exit a loop early?
A: You can use the break statement. When the program encounters break, it will immediately exit the current loop and continue execution at the first statement after the loop.

Q: How can I skip the current iteration and move to the next one?
A: You can use the continue statement. When the program encounters continue, it skips the rest of the code in the current iteration and jumps to the beginning of the next one.

Leave a Comment

About RadiantRiva

Your go-to resource for coding tutorials, developer guides, and programming tips.

Learn More

Quick Links

Follow Us

Newsletter

Get coding tips, tutorials, and updates straight to your inbox.