Iteration: FOR · Iteração: FOR
FOR repeats a fixed number of times
- A
FORloop counts from a start value to an end value. NEXTmarks the end of the loop body.
FOR I ← 1 TO 5
OUTPUT I // 1, 2, 3, 4, 5
NEXT I
A running total
- Start a total at 0, then add to it inside the loop.
Total ← 0
FOR I ← 1 TO 10
Total ← Total + I
NEXT I
OUTPUT Total // → 55
Trace the running total · Rastreie o total acumulado
A FOR loop repeats a set number of times. Step through and watch Total grow. · Um loop FOR repete um número fixo de vezes. Passe por ele e observe Total crescer.
STEP changes the count
STEPsets how much the counter changes each pass.STEP -1counts down.
FOR I ← 5 TO 1 STEP -1
OUTPUT I // 5, 4, 3, 2, 1
NEXT I
Watch out · Atenção
- Use
FORwhen you know how many times to repeat; useWHILEwhen you do not. - The counter (
I) andNEXT Imust use the same · mesmo name.
Common mistakes
FOR I ← 1 TO N ... NEXT Iruns · executa ntimes, including both ends.- The counter changes automatically each turn.
Now you try
- Use
FOR ... NEXT. Type<-for←. - Press Check answer to test it.
Use a FOR loop to output the numbers 1 to · até 5, one per line. · Use um loop FOR para imprimir os números 1 a 5, um por linha.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Use a FOR loop to add up 1 to · até 10, then output the total (it is 55). · Use um loop FOR para somar de 1 a 10, depois saia com o total (é 55).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Read an INTEGER N, then output N × 1, N × 2, N × 3 (one per line). For input 4, output 4, 8, 12. · Leia um INTEGER N, então imprima N × 1, N × 2, N × 3 (um por linha). Para entrada 4, imprima 4, 8, 12.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.