Control flow of a loop

Hello, I was thinking about the flow of nested for loops. So before asking my doubt let us suppose we have 3 for loops, one inside the other.

for( …){

 for( ...){

      for( ...){

}

}

}

As shown above. So how the flow of these loops will work. I mean that when will a loop will execute itself.

Say 3 loops is

for(int i=1;i<=2;i++){
         for(int j=3;j<=4;j++){
                   for(int k=5;k<=6;k++){
                              cout<<i<<" "<<j<<" "<<k<<endl;
                   }  
         }        
}

Here you will get output

1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6

Observe this , if you don’t understand then let me know .

1 Like

Well this was really a good example. Thank u very much for creating more clear image of for loops in my mind.

1 Like

I want to ask one more thing. For that let me write code on ide and I will share it soon.

Alright @yashsharma4304.

I know it takes me a long time to write this code because I was trying to understand it. Will you please explain me the working of this code deeply.

Hey @yashsharma4304
Outer loop is self explanatory
There are n rows in pattern so we are running it for n times

Now coming to Inner loops (In pattern Inner loops means working for each row at a time)
1st inner loop

So First observe that in 1st row there are n-1 space then in next n-2 then in next n-3 and so on
So first loop print spaces n-row times

.
Now observe that each row is first printing increasing sequence followed by dec seq.So we break each seq in a loop .
2nd Inner loop for increasing seq
Here observe inc seq starts from row number and print for row times

3rd loop for decreasing sequence
Here observe that it starts from 2*row-2 and print for row -1 times

1 Like

In pattern Inner loops means working for each row at a time

So it means inner loops are only working for a single row when outer loop is executed once. And when outer loop will execute next time, the row will be updated and all inner loops will start working on that row.

Well explained. Thank you.

yes exactly …:slight_smile:
I hope this resolves your query , if it does then please hit a like and mark this doubt as resolved :slight_smile:

1 Like