Thuta Learning
BasicProgrammingbeginner

Loops (For, While)

Relax. We'll talk through this in plain words — no textbook voice.

A loop lets you run a block of code over and over. Whether you're printing items from a list, tallying up a score, reading lines from a file, or running a game loop, skip the loop concept and your code will balloon into duplication.

cpp
#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 3; i++) {
        cout << "For loop count: " << i << endl;
    }

    int countdown = 3;
    while (countdown > 0) {
        cout << "Countdown: " << countdown << endl;
        countdown--;
    }
    return 0;
}

for loops have three parts: initialization, condition, and update. A while loop keeps running as long as its condition stays true. In the countdown example, leaving out countdown-- means the condition never stops being true — and you get an infinite loop.

You should see
For loop count: 1 For loop count: 2 For loop count: 3 Countdown: 3 Countdown: 2 Countdown: 1

Info

If you know the number of iterations up front, use for; if it should keep running based on a condition instead, while is the better fit.

Easy traps

  • Forgetting to update the loop variable, writing the condition wrong, or mixing up < and <= — these are all classic causes of off-by-one errors.
Loops (For, While) | Thuta Learning