Nested Loops
A nested loop means putting one loop inside another. In C, you can use for, while, or do-while loops inside each other to perform repeated tasks within a repeated task.
Syntax:
for (int i = 1; i <= outer_limit; i++) {
for (int j = 1; j <= inner_limit; j++) {
// inner loop code
}
// outer loop code
}
Example: Print Rectangle of Stars
#include <stdio.h>
int main() {
int rows = 3, cols = 5;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
Output:
*****
*****
*****
##Example: Multiplication Table
Let's create a multiplication table using nested loops:
#include <stdio.h>
int main() {
printf("Multiplication Table (1-5):\n");
for (int i = 1; i <= 5; i++) { // Outer loop
for (int j = 1; j <= 5; j++) { // Inner loop
printf("%d x %d = %d\t", i, j, i * j);
}
printf("\n"); // New line after each row
}
return 0;
}
Output:
1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 1 x 4 = 4 1 x 5 = 5
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 2 x 4 = 8 2 x 5 = 10
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 3 x 5 = 15
4 x 1 = 4 4 x 2 = 8 4 x 3 = 12 4 x 4 = 16 4 x 5 = 20
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
How It Works
- Outer loop starts with
i = 1 - Inner loop runs completely from
j = 1toj = 5 - Outer loop moves to
i = 2 - Inner loop runs completely again from
j = 1toj = 5 - This continues until the outer loop finishes
Pattern Printing Example
Nested loops are perfect for creating patterns:
#include <stdio.h>
int main() {
int rows = 5;
// Print a right triangle of stars
for (int i = 1; i <= rows; i++) { // Outer loop for rows
for (int j = 1; j <= i; j++) { // Inner loop for columns
printf("* ");
}
printf("\n");
}
return 0;
}
Output:
*
* *
* * *
* * * *
* * * * *
Different Loop Combinations
You can mix different types of loops:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 3) { // Outer while loop
printf("Outer loop: %d\n", i);
for (int j = 1; j <= 2; j++) { // Inner for loop
printf(" Inner loop: %d\n", j);
}
i++;
}
return 0;
}
Key Points to Remember
| Aspect | Description |
|---|---|
| Execution Order | Inner loop completes fully before outer loop advances |
| Total Iterations | Outer iterations × Inner iterations |
| Performance | Can be expensive with large datasets |
| Use Cases | 2D arrays, patterns, tables, matrix operations |
Common Pitfalls
- Infinite loops: Make sure both loops have proper termination conditions
- Variable scope: Inner loop variables are only accessible within the inner loop
- Performance: Nested loops can be slow with large numbers of iterations
Think of nested loops like reading a book with chapters and pages - you read all pages in chapter 1, then all pages in chapter 2, and so on. The outer loop is the chapters, and the inner loop is the pages!