Nested loops (Lesson-17)

A loop inside a loop is called a nested loop. Let's take an example to display a square of asterisk on the screen. We will input the height of the square from the user.
*Type the above code yourself in the IDE, execute it and see its output

In the above code, the outer loop determines the number of lines of asterisks. It will execute the inner loop a specific number of times. The inner loop is responsible for how many asterisks are present on one line. Let's change the above code. We will now display a rectangle. We will input the height of the rectangle and its width. The outer loop is responsible for controlling the height of the rectangle and the inner loop is responsible for controlling its width.
 *Type the above code yourself in the IDE, execute it and see its output

Let's dive into more difficult problems. We will write a program to display a pattern like this:
*
**
***
****
*****
We will input the height of this pattern from the user.
To solve any programming problem, the first step is to analyze it. Now let's pay attention to the above pattern which we are supposed to display. On the line number one, there is one asterisk, on the line number 2, there are 2 asterisks. In short, we can say that the width of the line (limit of the inner loop) is equal to the number of the line (current value of the outer loop). Let's see
 *Type the above code yourself in the IDE, execute it and see its output


Now let's see a more complex problem:
Write a program to display a pattern like this
*0000
**000
***00
****0
*****
We will input the height of this pattern from the user.

Before seeing the solution, try to solve the problem yourself.

The height of the example pattern is 5. On the line 1, there is 1 asterisk and 5-1=4 zeros. On the line 2, there are 2 asterisks and 5-2=3 zeros and so on.

 *Type the above code yourself in the IDE, execute it and see its output


Important Thing: You can nest as many loops as you wish. It means that there can be any number of loops inside another loop.

Practice Corner:

  • Put this lesson aside and code all the practice programs yourself without looking at the code given in this lesson.
  • Write a program to display the pattern like this:

You will input the height and width of this pattern from the user
  • Write a program to display a triangle like this:

000000000000
00000000000
0000000000
000000000
00000000
0000000
000000
00000
0000
000
00
0
You will input the height of the pattern from the user



  • Write a program to display a triangle like this:

  • You will input the height of the pattern from the user
    • Write a program to display a triangle like this:
    You will input the height of the pattern from the user

    Post a Comment

    0 Comments