The for Loop

The for loop is designed for situations where the number of iterations is known. It allows initialization, condition, and increment/decrement all in one line.

Syntax

for (initialization; condition; update)
    statement;

Example: Countdown

// countdown using a for loop
#include <iostream>
using namespace std;

int main() {
    for (int n = 10; n > 0; n--) {
        cout << n << ", ";
    }
    cout << "liftoff!\n";
}

Output:

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, liftoff!

How It Works

  1. Initialization: runs once before the loop starts (e.g., int n = 10;)
  2. Condition: checked before every iteration (n > 0)
  3. Update: runs after every iteration (n--)
  4. Statement: runs if condition is true (cout << n << ", ";)

Variations

All three parts are optional, but semicolons are required.

for (; n < 10; )    // no init or update
for (; n < 10; ++n) // update only
Caution

A missing condition creates an infinite loop.

Range-Based for Loop

Iterates automatically over each element in a range (like arrays or strings):

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

int main() {
    string str {"Hello!"};
    for (char c : str)
        cout << "[" << c << "]";
    cout << '\n';
}

Output:

[H][e][l][l][o][!]

You can use auto to automatically detect the element type, the effect is the same.

for (auto c : str)
    cout << "[" << c << "]";