Nested loops
- C course
- Beginner
- Lesson 46/116
- 5 min
Learn to print matrices and tables with nested for loops.
Nested loops
Putting a loop inside another loop creates a nested loop. For each iteration of the outer loop, the inner loop runs completely.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
printf("%d-%d ", i, j);
}
printf("\n");
}Output: 1-1 1-2 1-3 / 2-1 2-2 2-3 / 3-1 3-2 3-3 (each row on a separate line). The outer loop produces rows, the inner produces columns; useful for matrices and tables.
Right triangle
With nested loops you can draw shapes from stars. When the inner loop's limit depends on the outer counter, you get a right triangle.
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}Output: *. The inner loop's bound is
**
***
****j <= i; each row has one more star. This shows the power of nested loops.
Practice Star right triangle
Write a C program. Write an outer for (int i = 1; i <= 4; i++) and inner for (int j = 1; j <= i; j++) loop. In the inner loop print printf("*");, at the end of the outer print printf("\n");. Put #include <stdio.h> at the top.
Starter code
#include <stdio.h>
int main(void) {
// Print a star triangle with nested for
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}Expected output
* ** *** ****
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Inner loop condition
for (int i = 0; i < 3; i++) {
for (int j = 0; ____; j++) {
printf("%d", j);
}
printf("\n");
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d", j);
}
printf("\n");
}
Explanation: The inner loop counts j from 0 to 3.
2 Nested loop concepts
| Term | Meaning |
|---|---|
outer loop |
Produces rows |
inner loop |
Produces columns |
i |
Outer counter |
j |
Inner counter |
3 How many iterations does a 3x3 nested loop do?
for (i=0; i<3; i++)
for (j=0; j<3; j++)
printf("*");- 3 iterations
- 6 iterations
- 9 iterations Correct answer
- 12 iterations
Explanation: 3 outer × 3 inner = 9 total iterations.