C Nested for Loops
In this page:
What is a Nested for Loop?
A nested for loop places one for loop entirely inside the body of another, and the inner loop runs through its full range once for every single iteration of the outer loop.
Example: What is a Nested for Loop?
#include <stdio.h>
int main() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("(%d,%d) ", i, j);
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Printing a Grid Pattern
Nested loops are the standard technique for printing two-dimensional patterns like grids or triangles, with the outer loop typically controlling rows and the inner loop controlling columns within each row.
Example: Printing a Grid Pattern
#include <stdio.h>
int main() {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
printf("* ");
}
printf("\n");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested Loops over a 2D Array
Iterating over a two-dimensional array almost always uses nested loops, with the outer loop's index selecting a row and the inner loop's index selecting a column within that row.
Example: Nested Loops over a 2D Array
#include <stdio.h>
int main() {
int grid[2][2] = {{1, 2}, {3, 4}};
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 2; col++) {
printf("%d ", grid[row][col]);
}
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Nested Loops with Different Bounds
The outer and inner loops in a nested pair don't need matching bounds, and the inner loop's bound can even depend on the outer loop's current variable, which is how growing or shrinking patterns are produced.
Example: Nested Loops with Different Bounds
#include <stdio.h>
int main() {
for (int i = 1; i <= 3; i++) {
for (int j = 0; j < i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Performance of Nested Loops
The total number of iterations in a nested loop is the product of the outer and inner loop counts, so nested loops over large ranges can quickly become expensive, an important consideration when reasoning about performance.
Example: Performance of Nested Loops
#include <stdio.h>
int main() {
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
count++;
}
}
printf("%d", count);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: