C Programming: Memory, Pointers and the Stack · Control Flow
Three loops: for when you know the count, while while a condition holds, and do-while that always runs once.
#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;
}sum is created on the stack with the value 0.i changes from 1 to 2.sum changes from 1 to 3.i changes from 2 to 3.sum changes from 3 to 6.i changes from 3 to 4.sum changes from 6 to 10.i goes out of scope and disappears.n is created on the stack with the value 20.steps is created on the stack with the value 0.n changes from 20 to 10.steps changes from 0 to 1.n > 1 to decide whether the loop keeps going.n changes from 10 to 5.steps changes from 1 to 2.n > 1 to decide whether the loop keeps going.n changes from 5 to 2.steps changes from 2 to 3.n > 1 to decide whether the loop keeps going.n changes from 2 to 1.steps changes from 3 to 4.n > 1 to decide whether the loop keeps going.tries is created on the stack with the value 0.} while (tries < 0); /* the body runs once even though the condition is false */.10 4 1.0.