Nested loops and patterns · Bucles anidados y patrones
A loop inside a loop
- You can put one loop inside another. The inner loop runs fully for each step of the outer loop.
- This is how you work with rows and columns, or compare every pair of items.
- If the outer loop runs
Rtimes and the inner runsCtimes, the inner body runsR × Ctimes.
Un bucle dentro de otro
- Puedes colocar un bucle dentro de otro. El bucle interior se ejecuta completamente por cada paso del bucle exterior.
- Así es como se trabaja con filas y columnas, o al comparar cada par de elementos.
- Si el bucle exterior se ejecuta
Rveces y el interiorCveces, el cuerpo del bucle interior se ejecutaR × Cveces.
Rows and columns
- Think of the outer loop as the row and the inner loop as the column.
- For a block of
*, the outer loop picks a row; the inner loop prints the stars in that row. - After the inner loop finishes a row, print a newline
\nto start the next row.
Filas y columnas
- Piensa en el bucle exterior como la fila y en el bucle interior como la columna.
- Para un bloque de
*, el bucle exterior selecciona una fila; el bucle interior imprime los asteriscos de esa fila. - Después de que el bucle interior termina una fila, imprime un salto de línea
\npara comenzar la siguiente fila.
Building a line, then a block
printf("*")prints one star without moving to a new line.- Print all the stars for one row first, then one
printf("\n")to end the row. - Repeat for every row, and the rows stack into a block.
Construir una línea, luego un bloque
printf("*")imprime un asterisco sin pasar a la siguiente línea.- Imprime primero todos los asteriscos de una fila, y luego un
printf("\n")para finalizar la fila. - Repite esto para cada fila, y las filas se apilarán formando un bloque.
#include <stdio.h>
int main(void) {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
printf("*");
}
printf("\n"); // end the row
}
return 0;
}
Counting with nested loops
- Nested loops also count pairs. To count pairs
(i, j)withi < j, start the inner loop ati + 1. - A counter inside the inner loop adds up the matches.
- Watch the start and end values — off-by-one mistakes are common here.
Contar con bucles anidados
- Los bucles anidados también sirven para contar pares. Para contar pares
(i, j)dondei < j, inicia el bucle interior eni + 1. - Un contador dentro del bucle interior suma los casos coincidentes.
- Presta atención a los valores de inicio y fin; los errores de "fuera de rango" (off-by-one) son comunes aquí.
Common mistakes
- The inner loop runs fully for each single turn of the outer loop.
- Check the bounds so a pattern has no extra or missing row.
Errores comunes
- El bucle interior se ejecuta completamente por cada vuelta simple del bucle exterior.
- Verifica los límites para asegurar que el patrón no tenga filas extras ni faltantes.
Now you try
- Use an inner
printfwithout\nto build a row, then aprintf("\n")to end it. - For the function task, do not write a
main— the checker provides one.
Ahora tú intentas
- Usa un
printfinterno sin\npara construir una fila, seguido de unprintf("\n")para finalizarla. - Para la tarea de función, no escribas un
main; el verificador proporcionará uno.
In main, use nested loops to print a 3×3 block of * — three stars on each of three lines. · En main, use bucles anidados para imprimir un bloque de 3×3 de * — tres asteriscos en cada una de las tres líneas.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
In main, print a left-aligned triangle of * that is 4 rows tall: row 1 has one *, row 2 has two, up to row 4 with four. · En main, imprima un triángulo alineado a la izquierda de * que tenga 4 filas: la fila 1 tiene un *, la fila 2 tiene dos, hasta la fila 4 con cuatro.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete int count_pairs(int n) so it returns how many pairs (i, j) satisfy 1 <= i < j <= n. Use nested loops (start the inner loop at i + 1). Do not · no write a main. · Complete int count_pairs(int n) para que devuelva cuántos pares (i, j) satisfacen 1 <= i < j <= n. Use bucles anidados (inicie el bucle interno en i + 1). No escriba un main.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.