Aral Code

Control Flow Lesson 8 of 17

C++ Loops — for, range-based for, while and do-while

Repeat code in C++ with for, range-based for, while and do-while loops, use break and continue, validate input with a loop, and build nested-loop patterns.

C++ has the three classic loops from C, plus a convenient range-based for loop for going through every item of a collection.

for

#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        cout << "7 x " << i << " = " << 7 * i << endl;
    }
    return 0;
}

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

Range-based for

#include <iostream>
#include <string>
using namespace std;

int main() {
    string subjects[] = {"Math", "Science", "English"};
    for (const string &s : subjects) {
        cout << "- " << s << endl;
    }
    int total = 0;
    for (int g : {88, 92, 79}) total += g;
    cout << "Total: " << total << endl;
    return 0;
}

Output

- Math
- Science
- English
Total: 259

Read it as "for each s in subjects". const string & avoids copying each string; it's the recommended style for strings and objects.

while

#include <iostream>
using namespace std;

int main() {
    int n = 2026, reversed = 0;
    while (n > 0) {
        reversed = reversed * 10 + n % 10;
        n /= 10;
    }
    cout << "Reversed: " << reversed << endl;
    return 0;
}

Output

Reversed: 6202

do-while

#include <iostream>
using namespace std;

int main() {
    int choice;
    do {
        cout << "[1] Play  [2] Scores  [0] Quit: ";
        cin >> choice;
        if (choice == 1) cout << "Starting game..." << endl;
        else if (choice == 2) cout << "High score: 9800" << endl;
    } while (choice != 0);
    cout << "Bye!" << endl;
    return 0;
}

Output

[1] Play  [2] Scores  [0] Quit: 2
High score: 9800
[1] Play  [2] Scores  [0] Quit: 0
Bye!

Input validation loop

When cin gets bad input, it enters a failed state and stops reading. This loop recovers and asks again:

#include <iostream>
#include <limits>
using namespace std;

int main() {
    int grade;
    while (true) {
        cout << "Grade (0-100): ";
        if (cin >> grade && grade >= 0 && grade <= 100) break;
        cout << "Invalid, try again." << endl;
        cin.clear();                                          // reset the error state
        cin.ignore(numeric_limits<streamsize>::max(), '\n');  // discard the bad line
    }
    cout << "Saved: " << grade << endl;
    return 0;
}

Output

Grade (0-100): ninety
Invalid, try again.
Grade (0-100): 105
Invalid, try again.
Grade (0-100): 90
Saved: 90

break and continue

#include <iostream>
using namespace std;

int main() {
    int stock[] = {40, 0, 120, 0, 35};
    for (int i = 0; i < 5; i++) {
        if (stock[i] == 0) continue;     // skip empty items
        if (stock[i] > 100) {
            cout << "Item " << i << " is overstocked, stopping." << endl;
            break;
        }
        cout << "Item " << i << ": " << stock[i] << endl;
    }
    return 0;
}

Output

Item 0: 40
Item 2 is overstocked, stopping.

Nested loops: a hollow box

#include <iostream>
using namespace std;

int main() {
    int w = 8, h = 4;
    for (int r = 0; r < h; r++) {
        for (int c = 0; c < w; c++) {
            bool edge = (r == 0 || r == h - 1 || c == 0 || c == w - 1);
            cout << (edge ? '#' : ' ');
        }
        cout << "\n";
    }
    return 0;
}

Output

########
#      #
#      #
########

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. What does for (int g : grades) do?
2. Why write const string &s in a range-based loop?
3. After cin >> x fails, what must you do before reading again?
4. Which loop always runs at least once?

By Sir Reyel · Last updated 2026-12-04