Loops: while, for, and accumulation · Laços: while, for e acumulação
Loops
- A loop repeats a block of code many times.
- Loops let you count, add up numbers, and do work without copying lines.
- In this lesson you learn the
whileloop and theforloop.
Laços
- Um laço repete um bloco de código várias vezes.
- Laços permitem contar, somar números e trabalhar sem copiar linhas.
- Nesta lição você aprende o laço
whilee o laçofor.
The while loop
- A
whileloop runs its block again and again while a condition istrue. - You need three parts: start a counter, test it, and change it inside the loop.
- If you never change the counter, the loop runs forever. Be careful.
O laço while
- Um laço
whileexecuta seu bloco novamente e novamente enquanto uma condição étrue. - Você precisa de três partes: iniciar um contador, testá-lo e alterá-lo dentro do laço.
- Se nunca alterar o contador, o laço roda para sempre. Cuidado.
public class Main {
public static void main(String[] args) {
int i = 1; // start
while (i <= 3) { // test
System.out.println("Line " + i);
i = i + 1; // change
}
}
}
The for loop
- A
forloop puts the start, test, and change on one line. - The shape is
for (start; test; change) { ... }. - It does the same job as the
whileabove, but it is shorter and clearer.
O laço for
- Um laço
forcoloca o início, teste e alteração em uma linha. - O formato é
for (start; test; change) { ... }. - Faz o mesmo trabalho do
whileacima, mas é mais curto e claro.
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
System.out.println("Line " + i);
}
}
}
Accumulation
- Accumulation means building up an answer step by step inside a loop.
- Use a variable that starts at
0and grows:sum = sum + i;. i++is a short way to writei = i + 1.sum += iis short forsum = sum + i.
Acumulação
- Acumulação significa construir uma resposta passo a passo dentro de um laço.
- Use uma variável que começa em
0e cresce:sum = sum + i;. i++é uma forma curta de escreveri = i + 1.sum += ié curto parasum = sum + i.
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i; // add each number
}
System.out.println(sum); // 15
}
}
Counting with a condition
- You can count how many times something is true.
- Start a counter at
0, and add1only when the test passes. - Here we count even numbers from 1 to 10.
Contando com uma condição
- Você pode contar quantas vezes algo é verdadeiro.
- Inicie um contador em
0, e adicione1apenas quando o teste passar. - Aqui contamos números pares de 1 a 10.
public class Main {
public static void main(String[] args) {
int count = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) { // % gives the remainder
count++;
}
}
System.out.println(count); // 5
}
}
Off-by-one care
- The most common loop bug is doing one too many or one too few steps.
i <= nincludesn.i < nstops beforen.- To loop from 1 to
n(and includen), usefor (int i = 1; i <= n; i++).
Cuidado off-by-one
- O bug de laço mais comum é fazer um passo a mais ou um passo a menos.
i <= nincluin.i < npara antes den.- Para loopar de 1 a
n(e incluirn), usefor (int i = 1; i <= n; i++).
public class Main {
public static void main(String[] args) {
int n = 4;
// i goes 1, 2, 3, 4 — four times, because of <=
for (int i = 1; i <= n; i++) {
System.out.println(i);
}
}
}
Common mistakes
for (int i = 0; i < n; i++)runsntimes;<=runs one extra.- Do not put a
;right afterfor(...).
Erros comuns
for (int i = 0; i < n; i++)rodanvezes;<=roda uma extra.- Não coloque um
;logo apósfor(...).
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Agora você tenta
- Cada tarefa pré-preenche a estrutura da classe — escreva seu código dentro do main, ou complete o método mostrado.
- Pressione Run para compilar e executar, depois Check answer.
- Seu código compila e roda no servidor, então até a primeira execução é rápida.
Loops and accumulation · Laços e acumulação
A loop repeats; an accumulator builds up across the passes. · Um laço repete-se; um acumulador constrói algo ao longo das passagens.
Use a for loop to print the numbers 1 to · até 5, each on its own line. · Use um laço for para imprimir os números 1 até 5, cada um em sua própria linha.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete sumTo(int n) so it returns the sum 1 + 2 + ... + n. For example sumTo(5) is 15. If n is 0 or less, return 0. · Complete sumTo(int n) para que ele retorne a soma 1 + 2 + ... + n. Por exemplo sumTo(5) é 15. Se n for 0 ou menos, retorne 0.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete countMultiples(int n, int k) so it returns how many numbers from 1 to · até n divide evenly by k (use % == 0). For example countMultiples(10, 3) is 3 (that is 3, 6, 9). · Complete countMultiples(int n, int k) para que ele retorne quantos números de 1 a n são divisíveis por k (use % == 0). Por exemplo countMultiples(10, 3) é 3 (isto é, 3, 6, 9).
Click Run to see the output here. · Clique em Executar para ver a saída aqui.