Nested for loop
Harapriya Mohanta
Nested for loop means:
→ a for loop inside another for loop
for (initialization;cond; inc/dec)
{
outer loop for(initialization;cond; inc/dec)
{
//innerloop
}
}
When i will use nested loops:
for(initialization;cond; inc/dec) Using one for loop, i can print
{ either linearly(means one row) or
//body vertically(one column)
}
*************
************* or
Harapriya Mohanta
How will i print these Patterns ?
To print these
******
types of Pattern,
******
“nested loop”
******
is needed
******
******
*
**
***
****
***** Harapriya Mohanta
How nested loops work?
How Nested for loop works:
TRUE
TRUE
Harapriya Mohanta
How Nested for loop works:
condition check
first,i initialized TRUE
for (int i = 1;i<=3; i++)
{
for(int j =1;j<=3; j++)
{
outer loop variable inner loop runs
}
} i=1 3 times
Harapriya Mohanta
How Nested for loop works:
for (int i = 1;i<=3; i++)
{
once inner loop gets terminated,
for(int j =1;j<=3; j++) control goes back to the outer loop
{
Harapriya Mohanta
How Nested for loop works:
Now i++; executed
now i =2; 2<=3(true)
for (int i = 1;i<=3; i++) again go inside the outer loop
{
outer loop variable inner loop runs
for(int j =1;j<=3; j++) i=2 3 times
{
}
That means, for each
} value of i, inner loop runs
maximum no. of times
Harapriya Mohanta
How Nested for loop works:
outer loop variable inner loop runs
for (int i = 1;i<=3; i++) i=1 3 times
{ i=4 3 times
for(int j =1;j<=3; j++) i=3 3 times
{
}
That means, when outer
} loop runs 3 times, my inner
loop will run 9 times.
Harapriya Mohanta
Patterns
Harapriya Mohanta
How will i print these Patterns ?
******
******
******
******
******
*
**
***
****
*****
Harapriya Mohanta
Outer loop print
ROW for (initialization;cond; inc/dec)
{
Inner loop print
for(initialization;cond; inc/dec) Column
{
//innerloop
}
}
Harapriya Mohanta
PATTERN 1 :
Figure out
******
****** How many rows i have to be printed?
******
****** How many columns to print on each row?
What to print on each row?
Harapriya Mohanta