 # Nested for loop

Nested means that there is a loop within a loop. A nested loop is executed, essentially, from the inside out.

• Each loop is like a layer and has its own counter variable, its own loop expression and its own loop body.
• In a nested loop, for each value of the outermost counter variable, the complete inner loop will be executed once.
``` for (i = 1; i <= 4; i++)
{   // outer loop
for (j = 1; j <= 5; j+=2)
{    // inner loop
k = i + j;
printf(“i=%d, j=%d, k=%d”, i, j, k);
}
}
```

i is the outer loop counter and j is the inner loop counter. The outer loop is executed 4 times, when i =1,2,3, and 4. For each i value the inner loop is executed three times. Since j=1,3, and 5 the inner loop is executed 4*3 or 12 times.

Output is:

``` i=1,   j=1,   k=2
i=1,   j=3,   k=4
i=1,   j=5,   k=6
i=2,   j=1,   k=3
i=2,   j=3,   k=5
i=2,   j=5,   k=7
i=3,   j=1,   k=4
i=3,   j=3,   k=6
i=3,   j=5,   k=8
i=4,   j=1,   k=5
i=4,   j=3,   k=7
i=4,   j=5,   k=9 ```

## General Form of Nested For Loop

```for (loop1_exprs)
{
loop_body_1a
for (loop2_exprs)
{
loop_body_2
}
loop_body_1b
} ```

How many nests can be used for nested for loops?

Ans:   Most compilers allow 15 nesting levels.