Loops: while, for, and accumulation · Bucles: while, for y acumulación
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.
Bucle
- Un bucle repite un bloque de código muchas veces.
- Los bucles te permiten contar, sumar números y realizar tareas sin copiar líneas.
- En esta lección aprenderás el bucle
whiley el buclefor.
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.
El bucle while
- Un bucle
whileejecuta su bloque una y otra vez mientras una condición seatrue. - Necesitas tres partes: iniciar un contador, evaluarlo y modificarlo dentro del bucle.
- Si nunca modificas el contador, el bucle se ejecutará indefinidamente. Ten 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.
El bucle for
- Un bucle
forcoloca la iniciación, la evaluación y la modificación en una sola línea. - La estructura es
for (start; test; change) { ... }. - Realiza la misma tarea que el
whileanterior, pero es más corto y 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.
Acumulación
- La acumulación significa construir una respuesta paso a paso dentro de un bucle.
- Usa una variable que empiece en
0y aumente:sum = sum + i;. i++es una forma abreviada de escribiri = i + 1.sum += ies abreviado 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.
Conteo con una condición
- Puedes contar cuántas veces algo es verdadero.
- Inicia un contador en
0, y suma1solo cuando la evaluación sea positiva. - Aquí contamos los números pares del 1 al 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 con el error de uno
- El error de bucle más común es ejecutar un paso de más o uno de menos.
i <= nincluyen.i < nse detiene antes den.- Para iterar desde 1 hasta
n(incluyendon), usafor (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(...).
Errores comunes
for (int i = 0; i < n; i++)se ejecutanveces; con<=se ejecuta una vez más.- No pongas un
;justo después defor(...).
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.
Ahora tú intentas
- Cada tarea prellena la plantilla de la clase — escribe tu código dentro de main, o completa el método mostrado.
- Presiona Ejecutar para compilar y correr, luego Verificar respuesta.
- Tu código se compila y ejecuta en el servidor, así que incluso la primera ejecución es rápida.
Loops and accumulation · Bucles y acumulación
A loop repeats; an accumulator builds up across the passes. · Un bucle se repite; un acumulador se construye a través de las pasadas.
Use a for loop to print the numbers 1 to · hasta 5, each on its own line. · Utilice un bucle for para imprimir los números 1 a 5, cada uno en su propia línea.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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 devuelva la suma 1 + 2 + ... + n. Por ejemplo, sumTo(5) es 15. Si n es 0 o menor, devuelva 0.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete countMultiples(int n, int k) so it returns how many numbers from 1 to · hasta 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 devuelva cuántos números del 1 al n se dividen exactamente por k (use % == 0). Por ejemplo, countMultiples(10, 3) es 3 (es decir, 3, 6, 9).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.