A for loop repeats work while a counter changes.

for `for (init; condition; step)` groups the loop setup, test, and update.
accumulator An accumulator variable carries a running value across loop iterations.

Loops

limit
loops.c
Replay: real traced execution (multi-file project)
#include <stdio.h>

int main(void) {
    int limit = 4;
    int total = 0;

    for (int i = 1; i <= limit; i++) {
        total += i;
    }

    printf("total=%d\n", total);
    return 0;
}
#include <stdio.h>

int main(void) {
    int limit = 3;
    int total = 0;

    for (int i = 1; i <= limit; i++) {
        total += i;
    }

    printf("total=%d\n", total);
    return 0;
}
#include <stdio.h>

int main(void) {
    int limit = 5;
    int total = 0;

    for (int i = 1; i <= limit; i++) {
        total += i;
    }

    printf("total=%d\n", total);
    return 0;
}
  1. limit ← 4, total ← 0

    3int main(void) {4    int limit→ 4 = 4; //@limit=3, 55    int total→ 0 = 0;
  2. total ← 1

    pass 1 of 4
    7for (int i1 = 1; i <= limit4; i++) {8    total→ 1 += i1;9}
    All 4 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
  3. printf("total=%d ", total);

    11    printf("total=%d\n", total10);12    return 0;13}
    outputtotal=10
  1. limit ← 3, total ← 0

    3int main(void) {4    int limit→ 3 = 3;5    int total→ 0 = 0;
  2. total ← 1

    pass 1 of 3
    7for (int i1 = 1; i <= limit3; i++) {8    total→ 1 += i1;9}
    All 3 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
  3. printf("total=%d ", total);

    11    printf("total=%d\n", total6);12    return 0;13}
    outputtotal=6
  1. limit ← 5, total ← 0

    3int main(void) {4    int limit→ 5 = 5;5    int total→ 0 = 0;
  2. total ← 1

    pass 1 of 5
    7for (int i1 = 1; i <= limit5; i++) {8    total→ 1 += i1;9}
    All 5 passes — pass 1 is the card above
    passitotal
    110 1
    221 3
    333 6
    446 10
    5510 15
  3. printf("total=%d ", total);

    11    printf("total=%d\n", total15);12    return 0;13}
    outputtotal=15

Follow the Loop

  1. limit starts at 4.
  2. total starts at 0.
  3. The loop adds 1, then 2, then 3, then 4.
  4. total becomes 10.
  5. The program prints total=10. | limit | numbers added | total | | --- | --- | --- | | 3 | 1, 2, 3 | 6 | | 4 | 1, 2, 3, 4 | 10 | | 5 | 1, 2, 3, 4, 5 | 15 |

Exercise: loops.c

Reproduce total=10, then use the pinned limits 3 and 5 to predict each total.