while Loops · Laços while
| English | Português |
|---|---|
| while loop/waɪl luːp/ | laço while |
| loop control variable/luːp kənˈtrəʊl ˈveərɪəbl/ | variável de controle de loop |
| infinite loop/ˈɪnfɪnət luːp/ | laço infinito |
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.
Repita enquanto verdadeiro
- Um loop while 当型循环 repete seu corpo enquanto uma condição permanece
true. while (i <= 5) { sum = sum + i; i++; }- Antes de cada passagem, o Java verifica a condição; se estiver
false, o loop termina. - Use
whilequando não souber antecipadamente quantas passagens serão necessárias.
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.
Teste antes de cada passagem
- A condição é testada antes do corpo ser executado cada vez.
- Se for
falsena primeira verificação, o corpo executa zero vezes. - Após cada passagem, a condição é reavaliada antes da próxima.
- Essa ordem "verifique, depois talvez execute" vale a pena memorizar.
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.
A variável de controle do loop
- Uma variável de controle de loop 循环控制变量 impulsiona o progresso em direção à parada.
- Inicialize-a antes do loop, use-a na condição e altere-a dentro do corpo.
icomeça em1, a condição verificai <= 5, ei++avança-a.- Sem uma alteração que eventualmente viole a condição, o loop nunca termina.
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.
Loops infinitos
- Um loop infinito 无限循环 ocorre quando a condição nunca se torna falsa.
- Esquecer
i++(ou atualizar a variável errada) aprisiona o programa para sempre. - O sinal: o loop não faz progresso em direção à sua condição de parada.
- Sempre certifique-se de que cada passagem mova a variável de controle em direção à saída.
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.
Um while verifica sua condição ANTES de cada passagem — então pode executar zero vezes. Se a condição já estiver false, o corpo nunca executa. E você deve alterar a variável de controle do loop dentro do corpo para que a condição eventualmente fique false; esquecer a atualização (ex.: sem i++) é o clássico loop infinito.
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.
Somando 1 a 5:
int i = 1, sum = 0;while (i <= 5) { sum = sum + i; i++; }- Passagens:
i=1sum=1,i=2sum=3,i=3sum=6,i=4sum=10,i=5sum=15; entãoi=6falha<= 5→ para.sumé15.
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.
Um loop while repete seu corpo enquanto uma condição é true, verificando antes de cada passagem (então pode executar zero vezes). Uma variável de controle de loop deve ser inicializada, testada e atualizada dentro do corpo para que o loop faça progresso — esquecer a atualização causa um loop infinito.
Summing 1 to 5 with while · Somando 1 a 5 com while
Each pass adds i to sum, then i++ moves toward the exit. · Cada passagem adiciona i a sum, depois i++ aproxima-se da saída.
A while loop checks its condition... · Um laço while verifica sua condição...
The condition is tested before each pass, so it can run 0 times. · A condição é testada antes de cada passagem, portanto pode rodar 0 vezes.
int i=1, sum=0; while (i<=5){ sum+=i; i++; } What is sum at the end? · int i=1, sum=0; while (i<=5){ sum+=i; i++; } Qual é sum no final?
1+2+3+4+5 = 15.
Forgetting to update the loop control variable inside the body usually causes... · Esquecer de atualizar a variável de controle do laço dentro do corpo geralmente causa...
With no progress, the condition never becomes false. · Sem progresso, a condição nunca se torna falsa.
If a while condition is false on the first check, the body runs zero times. · Se a condição while for falsa na primeira verificação, o corpo roda zero vezes.
Test-before-each-pass means it can run 0 times. · Testar antes de cada passagem significa que pode rodar 0 vezes.
A loop that never stops because its condition never becomes false is an ___ loop (one word). · Um laço que nunca para porque sua condição nunca se torna falsa é um laço ___ (uma palavra).
An infinite loop makes no progress toward stopping. · Um laço infinito não avança em direção à parada.