while Loops
| English | Chinese | Pinyin |
|---|---|---|
| while loop | 当型循环 | dāng xíng xún huán |
| loop control variable | 循环控制变量 | xún huán kòng zhì biàn liàng |
| infinite loop | 无限循环 | wú xiàn xún huán |
Repeat while true
- A while loop 当型循环 repeats its body as long as a condition stays
true. while (i <= 5) { sum = sum + i; i++; }- Before each pass, Java checks the condition; if
false, the loop ends. - Use
whilewhen you don't know in advance how many passes you'll need.
Test-before-each-pass
- The condition is tested before the body runs each time.
- If it's
falseon the very first check, the body runs zero times. - After each pass, the condition is re-checked before the next.
- This "check, then maybe run" order is worth memorizing.
The loop control variable
- A loop control variable 循环控制变量 drives progress toward stopping.
- Initialize it before the loop, use it in the condition, and change it inside the body.
istarts at1, the condition checksi <= 5, andi++moves it forward.- Without a change that eventually breaks the condition, the loop never ends.
Infinite loops
- An infinite loop 无限循环 happens when the condition never becomes false.
- Forgetting
i++(or updating the wrong variable) traps the program forever. - The tell: the loop makes no progress toward its stopping condition.
- Always make sure each pass moves the control variable toward the exit.
A while checks its condition BEFORE each pass — so it can run zero times. If the condition is already false, the body never runs. And you must change the loop control variable inside the body so the condition eventually turns false; forgetting the update (e.g. no i++) is the classic infinite loop.
Summing 1 to 5:
int i = 1, sum = 0;while (i <= 5) { sum = sum + i; i++; }- Passes:
i=1sum=1,i=2sum=3,i=3sum=6,i=4sum=10,i=5sum=15; theni=6fails<= 5→ stop.sumis15.
A while loop repeats its body while a condition is true, checking before each pass (so it may run zero times). A loop control variable must be initialized, tested, and updated inside the body so the loop makes progress — forgetting the update causes an infinite loop.
Summing 1 to 5 with while
Each pass adds i to sum, then i++ moves toward the exit.
A while loop checks its condition...
The condition is tested before each pass, so it can run 0 times.
int i=1, sum=0; while (i<=5){ sum+=i; i++; } What is sum at the end?
1+2+3+4+5 = 15.
Forgetting to update the loop control variable inside the body usually causes...
With no progress, the condition never becomes false.
If a while condition is false on the first check, the body runs zero times.
Test-before-each-pass means it can run 0 times.
A loop that never stops because its condition never becomes false is an ___ loop (one word).
An infinite loop makes no progress toward stopping.