The while Loop
Part of: Iteration
Why Loops Exist Iteration means repeating a block of code. Instead of copying statements over and over, a loop runs the same code while a condition stays true. The simplest loop in Java is the while loop . How a while Loop Works A while loop checks its boolean condition before each pass. If the condition is true, the body runs; then control jumps back to re-check the condition. If the condition is false at the start, the body never runs at all. This prints 1 through 5. Every counted loop has three moving parts: - Initialization : int i = 1; (before the loop) - Condition : i <= 5 (tested each pass) - Update : i++ (inside the body) The Infinite Loop Trap You must change something inside the body so the condition eventually becomes false, or you create an infinite loop that never stops: The fix is always to make progress toward ending the loop. Sentinel-Controlled Loops A while loop shines when you do not know the number of repetitions ahead of time. A sentinel is a special value that signals "stop": This keeps reading numbers and adding them until it sees -1. Because the loop condition is tested at the top, choosing the right initial value and update is critical, always trace the fir
Challenge: Countdown with while