What is a Nested Loop?
A nested loop means:
One loop inside another loop.
- The outer loop controls how many times the inner loop runs.
- The inner loop completes all its iterations for each iteration of the outer loop.
Simple Definition
A loop written inside the body of another loop is called a nested loop.
Basic Structure
for (outer; condition; update) {
for (inner; condition; update) {
// statements
}
}The same concept applies to:
forinsideforwhileinsidewhiledo–whileinsidefor, etc.
Flow Chart
How Nested Loops Work
- Outer loop starts
- Inner loop runs completely
- Inner loop finishes
- Outer loop updates
- Inner loop runs again
- Process repeats
Simple Example
Print a 3×3 star pattern
c
1#include <stdio.h>
2
3int main() {
4 int i, j;
5
6 for (i = 1; i <= 3; i++) {
7 for (j = 1; j <= 3; j++) {
8 printf("* ");
9 }
10 printf("\n");
11 }
12
13 return 0;
14}Output
* * *
* * *
* * *Step-by-Step Explanation
i(outer loop) runs 3 times- For each
i,j(inner loop) runs 3 times - Total prints = 3 × 3 = 9 stars
Real-Life Analogy
- Days (outer loop)
- Classes per day (inner loop)
For every day, all classes are completed.
