Lesson 17: while loop
Sometimes you want to repeat an action several times. while (condition) { ... } runs the block again and again as long as the condition is true. You need a counter (like int i) that changes inside the loop — otherwise the condition never becomes false and the loop runs forever. i++ adds 1 to i.
while is like repeating 'as long as I haven't arrived — take another step'. Without advancing the counter, you're stuck forever.
- while (condition)
- Repeats the block as long as the condition is true.
- counter
- A variable (like i) that tracks how many times we've looped and changes each round.
- i++
- Adds 1 to i. Shorthand for i = i + 1.
- infinite loop
- If the condition never becomes false (e.g. you forget i++), the loop never stops.