C/C++ Arena

Step 6 of 7

Nested loops

A loop's body can contain another loop. The inner loop runs completely, from start to finish, during each pass of the outer loop. If the outer loop runs 3 times and the inner loop 4 times, the inner body runs 12 times.

Nested loops are how you work with anything two-dimensional: rows and columns, a grid, a table.

#include <stdio.h>

int main(void) {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 4; col++) {
            printf("%3d", row * col);
        }
        printf("\n");
    }
    return 0;
}
  1  2  3  4
  2  4  6  8
  3  6  9 12

(%3d pads each number to 3 characters wide so the columns line up.)

How to think about it

The inner loop's limit can depend on the outer counter. For example, for (int col = 1; col <= row; col++) makes row 1 have one column, row 2 two columns, and so on, which is how you build triangle shapes.

Use different counter names for each level (row and col, or i and j). Reusing the same name is a common bug.

Your turn: read n and print a right triangle of # with n rows. For n = 4:

#
##
###
####

Previous: do-while Next: One character at a time