In computer programming, a nested loop is a control flow statement where one or more loops are nested inside another loop. The inner loop runs a given number of times, and the outer loop runs according to the number of iterations specified by the inner loop. The most common type of nested loop is the for loop, which is used to iterate over a given sequence of values.
A nested for loop is often used to print patterns or designs. For example, the following code prints a rectangle made up of asterisks (*):
for i in range(5):
for j in range(5):
print(““, end=””) print()
Loops are one of the most important tools in programming. Loops allow us to repeat a set of instructions until a certain condition is met. There are two types of loops in Python – the for loop and the while loop. In this tutorial, we will learn about nested loops in Python.
Printing a Rectangle
To print a rectangle using nested loops, we first take the number of rows and columns as input from the user. Let the number of rows be ‘r’ and columns be ‘c’. We run two nested FOR loops. The loop variable ‘i’ is initialized with 1 and is incremented until it becomes equal to r. The inner loop variable ‘j’ is initialized with 1 and is incremented until it becomes equal to c. Inside both these loops, we print star character ‘‘.
After the inner loop is completed, we print a new line character so that next row gets printed on the next line.
A nested loop is a loop inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop”:
Print a rectangle of asterisks or any other character where the user specifies the width and height:
Width = 4, height = 3