Nested Loops

Loop with in an another loop is called as nested loops. Nested loops are used to print matrices or star patterns or number patterns etc. Let us see few set of nested loop examples for better understanding. 

In competitive programming, nested loops are not recommended for high input problem statements. It will lead to Time limit exceeded error due to large data input.

Syntax:

for iterating_var in sequence:
   for iterating_var in sequence:
      statement(s)
   statement(s)

Example:
Program to print the following right angle triangle star pattern
*
**
***
****

r = int(input("enter no.of rows \n"))  # reads a no. from user
for i in range(r):  # represents the rows
	for j in range(i+1):  # represents the number of columns in every row
		print("*",end="")  # prints *
	print()  # brings the cursor to the next line
Output:
enter no.of rows
4
*
**
***
****

Example:
Program to print the following right angle triangle number pattern
1
23
456
78910

r = int(input("enter no.of rows \n"))  
c = 1
for i in range(r+1):
	for j in range(1,i+1):
		print(c,end="")
		c=c+1	
	print()
Output:
enter no.of rows
4 1
23
456
78910

Example:
Program to print the following right angle triangle star pattern
    *
   **
 ***
****

r = int(input("enter no.of rows \n"))  # reads a no. from user
m =r  # assigns r to m
for i in range(r):  # represents the rows
	for s in range(m-1):  # represents the spaces
		print(" ",end="")
	m=m-1
	for j in range(i+1):  # represents the number of columns in every row
		print("*",end="")  # prints *
	print()  # brings the cursor to the next line
Output:
enter no.of rows 
4
*
**
***
****