Back to Top

Friday 17 April 2015

Begginer's Guide to C++- Chapter 5.1: Nesting in Loops

Today, we will learn nesting with loops. It is used to make some pretty spectacular programs, and I hope you will be able to make them too after reading this post!

Let us first see how the compiler executes the following statements-

for(i=0;i<5;i++)         //1
     {for(j=0;j<5;j++) //2
           {cout<<"@";
             }
      cout<<'/n';
      }

The output for the above will be
@@@@@
@@@@@
@@@@@
@@@@@
@@@@@

First, the compiler enters loop 1, the value of i in this case is 0. It then enters the second loop, which keeps on printing @ until j=5, after which loop no. 1 runs again with the value of i being 1.

This loop will again start loop no. 2, which will print @ 5 times again. This process continues till i=5.

Therefore, we conclude that each iteration will give the output as- @@@@@

Now, we will try to print
1
12
123
1234
12345

<---TRY TO SOLVE IT BEFORE READING BELOW--->

for(i=1;i<=5;i++)      // Loop1
     {for(j=1;j<=i;j++)// Loop2
            {cout<<j;
            }
      cout<<'/n';
      }

What is basically happening here?
Let us go through the first through iterations.

Initially the value of i is 1, and the value of j is also 1. Also, we notice that Loop2 will run only once, as j should be less than or equal to 1.

Output: 1

Now Loop1 will run again, but this time the value of i will be 2. So j should be less than  equal to 2. So Loop2 will now run twice.

Output: 1
            12

And the loop cycle goes on like this. I hope that this concept of nesting is clear to you, and you can ask any doubts related to it in the comments below, I will be happy to get back to you.

Q1. Print, using for loops-
1. 1
   23
   456
   78910

2. A
   BC
   DEF
   GHIJ

3. 12345
   1234
   123
   12
   1

4. 54321
   4321
   321
   21
  1

5.
   1
  121
12321
1234321
12321
 121

   1