Nested Loop
☞ Loop inside a loop is known as a nested loop.
☞ Once the condition of the outer loop is true, the control is transferred to the inner loop. The inner loop is terminated first and then the outer loop terminates.
Example 1 :
#To illustrate nested while loop
i = 1
while i<=2:
j=1
while j<=2:
print("inspirewebsoft")
j = j + 1
i = i + 1
Output :
inspirewebsoft
inspirewebsoft
inspirewebsoft
inspirewebsoft
Explanation :
- i and j are initialized to 1.
- The outer while loop runs as long as i is less than or equal to 2.
- Inside the outer loop, the inner while loop runs as long as j is less than or equal to 2.
- Inside the inner loop, the string "inspirewebsoft" is printed.
- After printing, j is incremented by 1.
- This inner loop continues until j is no longer less than or equal to 2.
- Once the inner loop completes its execution, the control goes back to the outer loop.
- Inside the outer loop, i is incremented by 1.
- The outer loop continues until i is no longer less than or equal to 2.
So, the output of this code will be the string "inspirewebsoft" printed 4 times, because the inner loop runs twice for each iteration of the outer loop.
Example 2 :
#To illustrate nested for loop
for i in range(1,3):
for j in range(1,3):
print("inspirewebsoft")
Output :
inspirewebsoft
inspirewebsoft
inspirewebsoft
inspirewebsoft
Explanation :
- The outer loop iterates over the values from 1 to 2 (range(1, 3)). The variable i takes on these values.
- For each iteration of the outer loop, the inner loop is executed.
- The inner loop also iterates over the values from 1 to 2 (range(1, 3)). The variable j takes on these values.
- For each combination of i and j, the string "inspirewebsoft" is printed.
- Since both loops run from 1 to 2, the string "inspirewebsoft" is printed a total of 4 times (2 times for each value of i, with j iterating through 1 and 2).
- This structure is an example of a nested loop, where one loop is contained inside another loop.
So, the output of this code will be the string "inspirewebsoft" printed 4 times, because the inner loop runs twice for each iteration of the outer loop.