Fundamentals 6 min read

Master C++ Loops: When to Use for, while, and do-while

Learn the three core C++ loop structures—for, while, and do-while—including their syntax, practical examples, control statements like break and continue, plus common pitfalls to avoid for reliable programming.

php Courses
php Courses
php Courses
Master C++ Loops: When to Use for, while, and do-while

Loop structures are essential control structures for repeating code blocks. C++ provides three basic loops: for, while, and do-while, each suited to different scenarios.

1. for loop

The for loop is the most common, ideal when the number of iterations is known.

for (initialization; condition; update) {
    // loop body
}

Basic example

#include <iostream>
using namespace std;

int main() {
    // Print numbers 1 to 10
    for (int i = 1; i <= 10; i++) {
        cout << i << " ";
    }
    return 0;
}

Nested for loop

For loops can be nested to handle multi‑dimensional data.

#include <iostream>
using namespace std;

int main() {
    // Print multiplication table
    for (int i = 1; i <= 9; i++) {
        for (int j = 1; j <= i; j++) {
            cout << j << "×" << i << "=" << i*j << "\t";
        }
        cout << endl;
    }
    return 0;
}

2. while loop

The while loop is used when the number of iterations is uncertain but must satisfy a condition.

while (condition) {
    // loop body
}

Basic example

#include <iostream>
using namespace std;

int main() {
    int num = 12345, count = 0;
    while (num != 0) {
        num /= 10;
        count++;
    }
    cout << "Number of digits: " << count << endl;
    return 0;
}

Infinite loop caution

A while loop can cause an infinite loop if the condition never becomes false.

// Dangerous infinite loop example
while (true) {
    // without a break, this runs forever
}

3. do-while loop

The do-while loop is similar to while but guarantees the body executes at least once.

do {
    // loop body
} while (condition);

Basic example

#include <iostream>
using namespace std;

int main() {
    int choice;
    do {
        cout << "1. Start Game
2. Settings
3. Exit
Choose: ";
        cin >> choice;
    } while (choice < 1 || choice > 3);
    cout << "You chose: " << choice << endl;
    return 0;
}

4. Loop control statements

C++ provides two important control statements:

break

Immediately terminates the current loop.

#include <iostream>
using namespace std;

int main() {
    // Find the first number divisible by 3
    for (int i = 1; i <= 10; i++) {
        if (i % 3 == 0) {
            cout << "Found: " << i << endl;
            break;
        }
    }
    return 0;
}

continue

Skips the current iteration and proceeds to the next loop cycle.

#include <iostream>
using namespace std;

int main() {
    // Print odd numbers from 1 to 10
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;
        }
        cout << i << " ";
    }
    return 0;
}

5. Loop selection guide

Use a for loop when the iteration count is known.

Use a while loop for condition‑controlled loops.

Use a do‑while loop when the body must execute at least once.

6. Common errors and tips

Avoid infinite loops; ensure the condition eventually becomes false.

Be aware of variable scope; variables declared in a for loop exist only within the loop.

Avoid unnecessary calculations inside the loop body to improve performance.

Use break and continue sparingly to maintain code readability.

Conclusion

Mastering C++'s three loop structures is fundamental. The for loop suits fixed‑count loops, while handles condition‑controlled loops, and do‑while guarantees at least one execution. Proper use of break and continue enhances control flow, and avoiding common pitfalls leads to more efficient, reliable code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Cprogramming fundamentalsLoopsfor loopwhile-loopcontrol statementsdo-while
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.