Lesson 6: while & do-while loops
Conditions gave us choice; loops give us repetition. while (condition) { ... } checks the condition before each round and runs the body again and again while it is true. For that you need a counter (like int i) that advances with i++ — otherwise the condition never turns off and the loop runs foreve
while is 'as long as you haven't arrived — take another step'. do-while is like tasting soup: you taste first (at least once!), and only then decide whether it needs more salt and taste again.
- while (condition)
- Checks the condition before each round; the body runs while the condition is true.
- do { } while (condition);
- Checks the condition at the end, so the body runs at least once. Note the trailing semicolon!
- counter & i++
- A variable tracking the rounds; i++ adds 1 to it each time.
- infinite loop
- If the condition never becomes false (e.g. you forgot i++), the loop never stops.
- input validation
- Asking for input again and again until it is valid — the classic do-while use.