Loops: while, for, and accumulation · Bucles: while, for y acumulación
Repeating work
- A loop runs the same block of code many times, so you don't copy it by hand.
- C has three loops:
while,for, anddo-while. They all repeat while a condition is true. - The condition is checked each time around. When it becomes false, the loop stops.
Trabajo repetitivo
- Un bucle ejecuta el mismo bloque de código muchas veces, por lo que no es necesario copiarlo manualmente.
- C tiene tres bucles:
while,forydo-while. Todos repiten mientras una condición sea verdadera. - La condición se verifica en cada vuelta. Cuando se vuelve falsa, el bucle termina.
while loops
while (test) { ... }checks the test first, then runs the block if it is true.- Something inside the block must eventually make the test false, or the loop never ends.
- Use
whilewhen you don't know in advance how many times you will repeat.
Bucle while
while (test) { ... }verifica la prueba primero, y luego ejecuta el bloque si es verdadera.- Algo dentro del bloque debe hacer que la prueba sea falsa eventualmente, o el bucle nunca terminará.
- Use
whilecuando no se sepa de antemano cuántas veces se repetirá.
for loops
- A
forloop puts three parts in one line:for (start; test; step). for (int i = 0; i < 5; i++)means: startiat0, keep going whilei < 5, add1each time.- Use
forwhen you are counting a known number of times.
Bucle for
- Un bucle
forcoloca tres partes en una sola línea:for (start; test; step). for (int i = 0; i < 5; i++)significa: iniciarien0, continuar mientrasi < 5, sumar1cada vez.- Use
forcuando esté contando un número conocido de veces.
#include <stdio.h>
int main(void) {
int total = 0;
for (int i = 1; i <= 4; i++) {
total = total + i; // accumulate: 1, then 3, then 6, then 10
}
printf("%d\n", total); // 10
return 0;
}
Accumulation and counting
- An accumulator is a variable that builds up a result across the loop, like
totalabove. - A counter adds
1each time something happens, to count matches. break;stops the loop early;continue;skips to the next round.
Acumulación y conteo
- Un acumulador es una variable que construye un resultado a través del bucle, como
totalarriba. - Un contador suma
1cada vez que ocurre algo, para contar coincidencias. break;detiene el bucle antes de tiempo;continue;salta a la siguiente vuelta.
Common mistakes
- Do not put a
;right afterfor(...)— it makes an empty loop. - Change the condition so the loop can end.
Errores comunes
- No coloque un
;justo después defor(...)— esto crea un bucle vacío. - Modifique la condición para que el bucle pueda terminar.
Now you try
- Set up your accumulator or counter before the loop, update it inside, and use it after.
- For the function tasks, do not write a
main— the checker provides one.
Ahora practique
- Configure su acumulador o contador antes del bucle, actualícelo dentro, y úselo después.
- Para las tareas de función, no escriba un
main; el verificador proporcionará uno.
Loops and accumulation · Bucles y acumulación
A loop repeats; a running total · suma acumulativa builds up each pass. · Un bucle se repite; un total acumulativo se construye en cada pasada.
In main, use a for loop to print the numbers 1 to · hasta 5, each on its own line. · En main, use un bucle for para imprimir los números 1 a 5, cada uno en una línea propia.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete int sum_to(int n) so it returns 1 + 2 + ... + n. Return 0 when n is 0 or negative. Do not · no write a main. · Complete int sum_to(int n) para que devuelva 1 + 2 + ... + n. Devuelva 0 cuando n sea · mar 0 o negativo. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete int count_multiples(int n, int k) so it returns how many numbers from 1 to · hasta n are divisible by k. Use % inside a loop. Do not · no write a main. · Complete int count_multiples(int n, int k) para que devuelva cuántos números de 1 a n son divisibles por k. Use % dentro de un bucle. No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.