A loop repeats a body until a condition fails. for is counting, while is 'as long as', do-while runs the body at least once.
A loop repeats a block of code until a condition fails. C has three spellings: for (count something), while (keep going as long as), and do-while (do it once, then maybe again). This run shows for; the cards explain the family.
C has three loop statements. This run uses for. The cards are the other two; the numbered column is the for-loop you are about to execute.
Best when the count is known. Init, test, and step live in one header: for (i = 1; i <= n; i++).
Best when you wait on a condition. You must change the variable yourself: while (n > 0) { printf("%d", n); n--; }.
Runs the body once before testing. Typical for a menu: show choices, then ask "again?". do { work(); } while (again);
initialize once
This happens before the first test, not on every pass.test before the body
If false, leave the loop. If true, run printf.loop body
This pass writes the current i to stdout.step, then test again
i becomes 2, then 3, then 4 — and 4 fails the test.Each step highlights the matching C line. Program output appears only when a line that prints actually runs.
Five questions. Pick one answer each, then Check answers. The correct choice turns green.
1. This foundation run uses which loop?
for (i = 1; i <= 3; i++).
2. do-while is different because:
Test at the bottom.
3. Forgetting i++ in a while that needs it causes:
The test never fails.
4. Output of this demo is:
printf each pass.
5. break inside a loop:
Jump out of the loop.