CodeMIRAI
0 XP

Loops

2 min read 6 runnable examples Quiz included

for

C++
#include <iostream>
using namespace std;

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

while

C++
#include <iostream>
using namespace std;

int main() {
    int n = 27, steps = 0;
    // the Collatz sequence: halve even numbers, 3n+1 for odd ones
    while (n != 1) {
        n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
        steps++;
    }
    cout << "27 reaches 1 after " << steps << " steps" << endl;
    return 0;
}

do-while

C++
#include <iostream>
using namespace std;

int main() {
    int guess;
    const int SECRET = 7;
    do {
        cout << "Guess (1-10): ";
        cin >> guess;
        if (guess != SECRET) cout << "Nope" << endl;
    } while (guess != SECRET);
    cout << "Got it!" << endl;
    return 0;
}

break and continue

C++
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 20; i++) {
        if (i % 3 != 0) continue;   // only multiples of 3
        if (i > 15) break;
        cout << i << " ";
    }
    cout << endl;
    return 0;
}

Patterns with nested loops

C++
#include <iostream>
using namespace std;

int main() {
    int n = 5;
    for (int row = 1; row <= n; row++) {
        for (int s = 0; s < n - row; s++) cout << " ";
        for (int k = 0; k < 2 * row - 1; k++) cout << "*";
        cout << endl;
    }
    return 0;
}

Digits of a number

C++
#include <iostream>
using namespace std;

int main() {
    int n, sum = 0, reversed = 0;
    cin >> n;
    while (n > 0) {
        int digit = n % 10;
        sum += digit;
        reversed = reversed * 10 + digit;
        n /= 10;
    }
    cout << "Digit sum: " << sum << ", reversed: " << reversed << endl;
    return 0;
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.