Q. What is nested loop? Explain with an example.


Answer :-

Nested Loops :-
A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop.

The following is an example of a nested loop, where a for loop is nested within another for loop.


for i in range (1, 6):
    for j in range (1, i):
        print ("*", end = ' ')
    print ()


Output :-

*
* *
* * *
* * * *

>>>

The inner for loop is executed for each value of i. The variable i takes values 1, 2, 3 and 4. The inner loop is executed once for i = 1 according to sequence in inner loop range (1, i) (because for i as 1, there is just one element 1 in range (1, 1) thus j iterates for one value, i.e., 1), twice for i = 2 (two elements in sequence range(1, i), thrice for i = 3 and four times for i = 4 While working with nested loops, you need to understand one thing and that is, the value of outer loop variable will change only after the inner loop is completely finished (or interrupted).

Post a Comment

You can help us by Clicking on ads. ^_^
Please do not send spam comment : )

Previous Post Next Post