While loops
EasyRepeat until a condition breaks
Problem
A while loop repeats as long as its condition stays true — ideal when you don't know the number of iterations up front. A do-while runs the body at least once before checking.
Keep repeating as long as a condition stays true.
The idea
A while loop repeats as long as its condition holds, which suits the cases where the iteration count is not known in advance — halving a number, walking a linked list, or reading until input runs out. The obligation it puts on you is to change something inside the body that will eventually make the condition false.
The trick
- If nothing in the body affects the condition, the loop never ends.
- `do { } while (…)` checks the condition afterwards, so the body always runs at least once.
- A while that halves its value each pass runs about log₂(n) times — the shape behind binary search.
Step 1 of 10. A while loop asks its question first: is 4073 still greater than 0? Values: —. n 4073.
1while (n > 0) {2 print(n % 10); // last digit3 n = n / 10; // drop it4}Input
- array
- [—]
Memory
- n
- 4073
- digit
- —
Check yourself
2 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- n = 13; while n > 0: print(n % 10); n = n / 10
- Output:
- 3 1
- Explanation:
- A while loop is for when you do not know the count in advance — here it stops when the digits run out.
Example 2
- Input:
- n = 0
- Output:
- (nothing printed)
- Explanation:
- The condition is tested before the first turn, so a while loop can run zero times.
Finished the walkthrough? Add it to your streak.