Introduction
Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.
Nested loops let you repeat actions inside other repeated actions. This helps when you work with tables or grids.
for (initialization; condition; update) { for (initialization; condition; update) { // code to repeat } }
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { printf("%d %d\n", i, j); } }
int i = 1; while (i <= 2) { int j = 1; while (j <= 3) { printf("%d %d\n", i, j); j++; } i++; }
This program prints a rectangle of stars with 3 rows and 4 columns using nested for loops.
#include <stdio.h> int main() { for (int row = 1; row <= 3; row++) { for (int col = 1; col <= 4; col++) { printf("* "); } printf("\n"); } return 0; }
Be careful with loop limits to avoid infinite loops.
Indent your code inside loops to keep it clear.
Nested loops run one loop inside another to repeat actions in layers.
They are useful for working with tables, grids, or pairs of data.
Always check your loop conditions to avoid mistakes.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// code
}
}for loop in C?for (int i = 1; i <= 2; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d%d ", i, j);
}
}for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
printf("%d%d\n", i, j);
}
}for (int i = 1; i <= 4; i++) {
for (int j = i; j <= 4; j++) {
for (int k = 1; k <= j; k++) {
printf("*");
}
}
}Pass the test and this pattern moves unknown