Codiqo

Learn C++ · lesson 19 of 61 · about 8 minutes

for Loops

Draw the hero's health bar ten characters at a time: count with for loops, and nest loops for rows and columns.

What you'll learn

  • Write a counting for loop
  • Count down and in steps
  • Nest loops

A health bar

The adventure prints Health: 85, but games show a bar: HP [########--]. It's always 10 characters, a # for every 10 health and a - for the rest. A loop that runs exactly 10 times, deciding one character each lap, is what a for loop is for.

Start; condition; step

for (int i = 0; i < 5; i++) sets i once, checks the condition before every lap, and runs the step after every lap. i only exists inside the loop.

Counting

#include <iostream>

int main() {
    for (int i = 0; i < 3; i++) std::cout << i << " ";
    std::cout << "\n";
    for (int i = 10; i > 0; i -= 4) std::cout << i << " ";
    std::cout << "\n";
}

Output

0 1 2
10 6 2

The health bar

#include <iostream>
#include <string>

int main() {
    int health = 75;
    std::string bar;
    for (int i = 0; i < 10; i++) {
        if (i < health / 10) {
            bar += '#';
        } else {
            bar += '-';
        }
    }
    std::cout << "HP [" << bar << "]\n";
}

Output

HP [#######---]

Loops inside loops

A loop can sit inside another loop: for every lap of the outer loop, the inner one runs all the way through. Rows and columns are the classic use.

A times table

#include <iostream>
#include <iomanip>

int main() {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 3; col++) {
            std::cout << std::setw(4) << row * col;
        }
        std::cout << "\n";
    }
}

Output

   1   2   3
   2   4   6
   3   6   9

Tip

health / 10 is integer division, so 75 / 10 is 7: seven # for 75 health, and a partly filled block doesn't count.

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.