DMarlon Studio

Lesson 9 · 9 of 20

for loops · C

Use C's for loop to count up and down, add things up, skip turns with continue, leave with break and nest one loop inside another.

C · for loops in DMarlon Studio: the example's code and its output in the terminal

`for` puts the three parts of a counting loop in one line: the start (int i = 1), the condition (i <= 5) and the step (i++). It does the same as a while, but more compactly. The variable i only exists inside the loop.

The step can be anything: n -= 2 counts down in twos. A for is also good for adding up: total starts at 0 and every day adds that day's sales, 20 + 3 * day, reaching 224 loaves.

`continue` jumps to the end of the turn and moves on to the next: seats that are multiples of 4 (seat % 4 == 0) are not printed. `break` leaves the loop altogether: once past seat 10 the loop ends, even though the condition goes up to 20.

A loop inside another goes through rows and columns. For each row, the inner loop runs five times. 'A' + row takes advantage of a char being a number: 'A' + 1 is 'B'.

Code · main.c

#include <stdio.h>int main(void) {    // for (start; condition; step): everything about the counter in one line.    for (int i = 1; i <= 5; i++) {        printf("%d x 7 = %d\n", i, i * 7);    }    // Counting down in steps of 2.    for (int n = 10; n > 0; n -= 2) printf("%d ", n);    printf("\n");    // Adding up: a bakery sells 20 loaves plus 3 more each day.    int total = 0;    for (int day = 1; day <= 7; day++) {        total += 20 + 3 * day;    }    printf("Loaves sold this week: %d\n", total);    // continue jumps to the next turn; break leaves the loop.    for (int seat = 1; seat <= 20; seat++) {        if (seat % 4 == 0) continue;  // every fourth seat is broken        if (seat > 10) break;         // only the first row is open        printf("seat %d ", seat);    }    printf("\n");    // A loop inside a loop: rows and columns of a cinema.    for (int row = 0; row < 3; row++) {        for (int col = 1; col <= 5; col++) printf("%c%d ", 'A' + row, col);        printf("\n");    }    return 0;}

Output · cc main.c -o main && ./main

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35
10 8 6 4 2 
Loaves sold this week: 224
seat 1 seat 2 seat 3 seat 5 seat 6 seat 7 seat 9 seat 10 
A1 A2 A3 A4 A5 
B1 B2 B3 B4 B5 
C1 C2 C3 C4 C5

Key points

  • for (start; condition; step) holds the whole counter.
  • An accumulator starts at 0 and adds on every turn.
  • continue moves to the next turn; break leaves the loop.
  • Nested loops go through rows and columns.

Exercise

Print the full 1 to 9 times table with two nested for loops, each number in a column 3 characters wide (%3d).