C While Loop
Repeat work while a condition remains true, change state each pass, and keep an obvious exit.
Use while when changing state defines the stop
A while loop continues until some state changes: tasks remaining, a retry count, or a validated input. Its condition appears at the top, so it may run zero times. That is often correct when there is no work to do. Prefer C For Loop when the repetition count is known before the first cycle.
Make a while loop finish
remaining controls the loop and remaining-- changes that same value each cycle.
Edit the program, predict its output, then run it.
Trace a while loop before you write it
Start with remaining = 3. The condition remaining > 0 is true, so the body prints 3 and remaining-- stores 2. After printing 1, the update stores 0; 0 > 0 is false, so the completion message prints. At the start of every pass, remaining is the number of tasks not yet reported—that repeated fact is a loop invariant.
Zero-cycle case
The body runs zero times. The statement after the loop still runs.
One-cycle case
The body runs once, then the update reaches the stopping boundary.
Failure case
The condition keeps reading the same positive value.
Use do-while only when one attempt must happen first
A do/while loop tests after its body, so the body runs at least once even if the condition is already false. That matches a prompt that must appear before the user can stop. If the work may legitimately happen zero times, use while.
Run a first check before testing again
The body prints once before checks < 2 is evaluated.
Edit the program, predict its output, then run it.
break and continue target the nearest loop
break leaves immediately. continue returns to the while condition. If you continue before the update, you can create an infinite loop. Put the state change where every path that should continue still performs it—or use a for loop whose update always runs.
Skip one cycle and stop after a found result
Increment happens before continue, so attempt still moves.
Edit the program, predict its output, then run it.
Independent lab: a retry limit
Write a loop that continues while attempt < 3, prints the attempt number, and increments. Then add a path that breaks early on a successful dummy condition. Prove that removing the increment would not finish.
Lesson review
whiletests first and may run zero times.- Name the initial state, the condition, and the update that can stop it.
do/whileruns at least once.continuemust not skip the update that makes progress.