Skip to content

Loops inside loops

Read · 1 of 4

The inner loop runs fully each time

With a loop inside a loop, the inner one runs from start to finish for every turn of the outer one. The outer loop usually picks the row, the inner one fills it.

Read this lesson as text

Rows and columns: patterns and tables with a loop inside a loop.

The inner loop runs fully each time

With a loop inside a loop, the inner one runs from start to finish for every turn of the outer one. The outer loop usually picks the row, the inner one fills it.

A small triangle

#include <stdio.h>

int main() {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= row; col++) {
            printf("*");
        }
        printf("\n");
    }
    return 0;
}
  1. Line 4: Row 1.
  2. Line 6: The inner loop runs once (col 1 to 1).
  3. Line 8: End the row.
  4. Line 6: Row 2: the inner loop runs twice.
  5. Line 8: End the row.
  6. Line 6: Row 3: three stars.
  7. Line 8: Done.

Exercise: Number triangle

Read n and print n rows. Row r holds the numbers 1 to r separated by spaces:

1

1 2

1 2 3

Exercise: Centred pyramid

Read n and print a pyramid of n rows. Row r has n − r spaces, then 2r − 1 stars. For n = 3:

*

***

*****