Loops
C gives you three ways to repeat a block of code, and picking the right one is mostly about where the "how many times" question gets answered — before the loop starts, somewhere in the middle, or only after running the body at least once.
for: when you know the count up front
A for loop packs three things into its parentheses, separated by semicolons: a starting point, a condition checked before every pass, and something that runs after every pass. It's the natural choice whenever you're counting through a known range:
#include <stdio.h> int main(void) { int n = 5; for (int i = 1; i <= 5; i++) { printf("%d x %d = %d\n", n, i, n * i); } return 0; }
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
Declaring i inside the parentheses (int i = 1) scopes it to the loop — it doesn't exist before the loop starts and doesn't leak out afterward, which keeps it from colliding with some other i you might need elsewhere in the same function.
while: condition-driven repetition
A while loop checks its condition before every pass and has no built-in counter — you're free to loop based on anything that can be true or false, including a value that changes for reasons unrelated to counting. This example also shows continue, which skips the rest of the current pass and jumps straight to the next condition check:
#include <stdio.h> int main(void) { int i = 0; int sum = 0; while (i < 10) { i++; if (i % 2 != 0) { continue; } sum += i; } printf("Sum of even numbers 1-10: %d\n", sum); return 0; }
Sum of even numbers 1-10: 30
Odd values of i hit the continue and skip straight past sum += i; only even values (2, 4, 6, 8, 10) actually get added, which is where the 30 comes from.
while loop is only as safe as whatever changes its condition. If nothing inside the loop body ever makes i < 10 false, the loop runs forever and the program hangs — the compiler won't warn you about this, since it can't know your intent.do-while: guaranteed at least once
while and for both check their condition before running the body, which means the body might not run even a single time. A do-while loop flips that order — it runs the body first, then checks the condition, so it always executes at least once regardless of what the condition would have said up front:
#include <stdio.h> int main(void) { int count = 5; do { printf("Countdown: %d\n", count); count--; } while (count > 0); printf("Liftoff!\n"); return 0; }
Countdown: 5 Countdown: 4 Countdown: 3 Countdown: 2 Countdown: 1 Liftoff!
This particular example would print the same thing with a plain while loop, since the condition happens to be true on the first check anyway. The distinction only shows up in practice when the starting condition could be false from the beginning — a menu that should display at least once before asking "run again?", for instance.