Module 3 · Decisions and Loops — topic 3 of 5
Loops: while, do-while and for
Loops repeat code. Learn the three C loops, how each checks its condition, how to write counting and sentinel loops, and how to avoid infinite and off-by-one loops.
Learning objectives
- Write while, do-while and for loops
- Choose the right loop for counting, sentinel and validation tasks
- Trace loop variables and avoid off-by-one errors
Definition
An iteration statement repeatedly executes a body while a controlling expression compares unequal to zero.whileandfortest before each iteration (entry-controlled);do-whiletests after (exit-controlled), so its body runs at least once.
Introduction
Printing a table, summing a list, retrying input until it is valid — anything that repeats is a loop. C has three loop statements that differ mainly in when they check the condition.
Every loop needs the same three ingredients: something that starts it (initialisation), something that keeps it going (the condition) and something that moves it towards the end (an update). Forgetting the update produces an infinite loop.
Why it matters
Loops are where programs spend almost all their time, and where most logic errors live. Being able to trace a loop by hand — writing down the variable values each iteration — is the most useful debugging skill a beginner can learn.
Pattern printing, digit manipulation and series problems in exams are all loop exercises.
Detailed explanation
`while (cond) body` checks the condition first. If it is false initially, the body never runs. Use it when you don't know in advance how many iterations are needed.
`do body while (cond);` runs the body first and checks afterwards, so it always runs at least once. It is ideal for menus and input validation. Note the semicolon after the condition.
`for (init; cond; update) body` gathers the three ingredients in one line. It is the natural choice for counting. Any part may be empty; for (;;) is an infinite loop.
Since C99 you can declare the counter inside the for: for (int i = 0; i < n; i++). That i exists only inside the loop.
Syntax
i < nwithistarting at 0 runs exactlyntimes.- The
do-whileends with a semicolon. - Keep the update next to the condition so infinite loops are easy to spot.
Code examples
Counting with for
1 x 7 = 7 2 x 7 = 14 3 x 7 = 21 4 x 7 = 28 5 x 7 = 35
Digits with while
5 digits, digit sum 10
More examples
Sentinel input and validation
72 88 150 64 -1
Enter marks, -1 to stop: ignored 150 3 marks, average 74.67
Step-by-step explanation
- The
whilecondition both reads a value and stops if reading fails or the sentinel -1 arrives. - Out-of-range marks such as 150 are reported and skipped with
continue. - Valid marks are added to
total(alongto avoid overflow) and counted. - After the loop, the program guards against dividing by zero when nothing was entered.
- (72 + 88 + 64) / 3 = 74.666…, printed as 74.67.
Expected output
Running “Sentinel input and validation” with the sample input shown prints exactly:
Practical applications
- Servers run an event loop that waits for and handles requests forever.
- Embedded devices run a
for (;;)super-loop that reads sensors and updates outputs. - Data processing reads records until end of file, a sentinel-controlled loop.
Best practices
- Prefer
forwhen the number of iterations is known;whilewhen it isn't;do-whilefor at-least-once. - Use half-open ranges
0 <= i < nfor arrays. - Trace small loops by hand in a table of variable values.
Common mistakes
Forgetting the update
Avoid
Prefer
i never changes, so the condition stays true forever.
Off-by-one with <=
Avoid
Prefer
Valid indexes are 0–4. i <= 5 writes past the end of the array — undefined behaviour.
Semicolon after for
Avoid
Prefer
The semicolon is the empty loop body; printf runs once after the loop. (With int i declared in the for, the misplaced version may not even compile if the body uses i.)
Important notes
- A loop whose condition can never become false is not automatically an error; the compiler may even assume a side-effect-free infinite loop terminates in some cases. Always make progress toward the exit.
- Using a
floatas a loop counter accumulates rounding error; count with integers.
Key takeaways
whileandfortest first;do-whiletests last and runs at least once.- Every loop needs initialisation, a condition and an update.
- Use
i < nfrom 0 for n iterations over an array.
Try it yourself
- 1Print the sum of the series 1 + 1/2 + 1/3 + … + 1/n for n read from input, to 4 decimal places.
- 2Write a
do-whilemenu that keeps showing options until the user enters 0. - 3Reverse the digits of an integer (e.g. 1234 → 4321) using a while loop.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
10 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerHow many times does this loop print "hi"?
- BeginnerWhat is printed?
- BeginnerThis loop never ends. Why? `int i = 0; while (i < 10) { printf("%d\n", i); }`