Repeat while a condition holds
Repeat while a condition holds
Some repetition depends on a condition rather than a known list. A while loop checks its condition before each body execution. A repeat-while loop checks after the body, so it runs at least once. This distinction matters for retries and input prompts.
The loop must make progress toward stopping, or it may run indefinitely. Track which value changes and when the condition observes that change. A condition false initially skips a while body but not a repeat-while body.
What you’ll learn
- Identify when a loop tests its condition.
- Explain why a counter update is necessary for termination.
Repeat while a condition holds in the example
Check remaining
Some repetition depends on a condition rather than a known list.
Check remainingPrint and decrement
The loop must make progress toward stopping, or it may run indefinitely.
Print and decrementStop at zero
The program prints 3, 2 and 1 while subtracting one after each display.
Stop at zero
Work through repeat while a condition holds
Save this complete program as main.swift and run it with the Swift toolchain. No separate input file is needed.
Swift · complete program
var remaining = 3
while remaining > 0 {
print(remaining)
remaining -= 1
}
print("Ready")Expected output
3
2
1
ReadyFollow the execution
The program prints 3, 2 and 1 while subtracting one after each display. The next condition sees zero and ends the loop. Ready then prints once. Omitting the subtraction would leave the condition true indefinitely.
Try this program in the Swift compiler. Paste the complete source above.
Practice: Repeat while a condition holds
Your task: What happens if remaining starts at zero?
Swift · complete program
var remaining = 3
while remaining > 0 {
print(remaining)
remaining -= 1
}
print("Ready")Worked answer
The while body runs zero times, and Ready prints immediately. A repeat-while version would run its body once before discovering the false condition.
Make progress toward stopping
Retries need limits and appropriate failure handling. Repeatedly checking a resource without waiting or an event mechanism can waste CPU time; this small counter is a teaching loop rather than a production polling design.
Check your decision
Repeat while a condition holds in practice
The while body runs zero times, and Ready prints immediately. A repeat-while version would run its body once before discovering the false condition. Retries need limits and appropriate failure handling.
Further reading: official Swift language guide.
Reaching the recap and completing the quizzes are separate milestones.