Nested Loops
Nested loops
Using of one loop inside another loop is called nested loop. In other words it is said as loop within the loop.
Syntax for the nested for loop
>>> for <variable> in <sequence>:
for <variable> in <sequence>: #body goes here |
The following are some of the examples of nested for loops
Ex 1 A sample program on nested for loop
Output
$
$ $ $ $ $ $ $ $ $ $ $ $ $ $ |
For the same above example the step count is taken as “2” and is shown in below
Output
$
$ $ $ $ $ $ $ $ |
Ex 2: A program to print the multiplication of ‘1’ and ’2’.
Output
1*1=1 1*2=2 1*3=3 1*4=4 1*5=5 1*6=6 1*7=7 1*8=8 1*9=9 1*10=10 2*1=2 2*2=4 2*3=6 2*4=8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20 |
Ex 3 A source code to print the pattern of numbers
Output
1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 |
Ex 4: To print the pattern of pyramid
Output
* * * * * * * * * * * * * * * |
Ex 5 Another pattern program of nested for loops
Output
* * * * * * * * * * * * * * * * * * * * * * * * * |
Syntax for the nested while loop
while expression:
while expression: statement(s) statement(s) |
The following are some of the examples of the nested while loops
Ex 1: A sample program on nested while loop
Output
2 , 4 3 , 5 |
Ex 2: To print prime numbers between 2 and 40
Output
2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime Executed |
Ex 3: A program to print inverted right angle triangle
Output
* * * * * * * * * * * * * * * |
Ex 4: A program to print the pattern of right angle triangle
Output
* * * * * * * * * * * * * * * |
Ex 5: A program to print the pattern of a string “Sudha”
Output
Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha Sudha |
Ex 6: Another example to print the pattern of two right angle triangles.
Output
* ** *** **** ***** * ** *** **** ***** |
Ex 7: A program with the combination of while and for loop
Output
Enter any number: 6 1 2 3 4 5 Enter any number: 3 1 2 Enter any number: 0 |
In the above example the user has to enter a number and then there prints all numbers less than that number. The process will continue until the user enters ‘0’