C Programming: Memory, Pointers and the Stack · Control Flow

for, while and do-while

Three loops: for when you know the count, while while a condition holds, and do-while that always runs once.

loops.c

#include <stdio.h>

int main(void) {
    int sum = 0;
    for (int i = 1; i <= 4; i++) {
        sum += i;
    }
    int n = 20;
    int steps = 0;
    while (n > 1) {
        n = n / 2;
        steps++;
    }
    int tries = 0;
    do {
        tries++;
    } while (tries < 0);           /* the body runs once even though the condition is false */
    printf("%d %d %d\n", sum, steps, tries);
    return 0;
}

Step by step

  1. sum is created on the stack with the value 0.
  2. for has three parts: start (i = 1), condition (i <= 4) and step (i++).
  3. sum = 0 + 1.
  4. i changes from 1 to 2.
  5. sum changes from 1 to 3.
  6. i changes from 2 to 3.
  7. sum changes from 3 to 6.
  8. i changes from 3 to 4.
  9. sum changes from 6 to 10.
  10. i goes out of scope and disappears.
  11. n is created on the stack with the value 20.
  12. steps is created on the stack with the value 0.
  13. while checks first: 20 > 1, so halve it.
  14. n changes from 20 to 10.
  15. steps changes from 0 to 1.
  16. C checks n > 1 to decide whether the loop keeps going.
  17. n changes from 10 to 5.
  18. steps changes from 1 to 2.
  19. C checks n > 1 to decide whether the loop keeps going.
  20. n changes from 5 to 2.
  21. steps changes from 2 to 3.
  22. C checks n > 1 to decide whether the loop keeps going.
  23. n changes from 2 to 1.
  24. steps changes from 3 to 4.
  25. C checks n > 1 to decide whether the loop keeps going.
  26. tries is created on the stack with the value 0.
  27. do-while runs the body before checking.
  28. Line runs: } while (tries < 0); /* the body runs once even though the condition is false */.
  29. It prints 10 4 1.
  30. The method returns 0.
  31. sum 10, 4 halvings (20 → 10 → 5 → 2 → 1), and 1 try.