Class xi nested loop with questions:
A nested loop is a loop inside another loop. Although all kinds of loops can be nested, the most common nested loop involves for loops. These loops are particularly useful when displaying multidimensional data. When using these loops, the first iteration of the first loop will initialize, followed by the second loop.
Question:
Write a Python program using nested for loops to print the following pattern:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Solution:
python
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=" ")
print()
Explanation:
- The outer loop controls the number of rows (5 in this case).
- The inner loop prints numbers from
1
to i
in each row. As the value of i
increases with each iteration, more numbers are printed on each line.
Example 2: Right-Angled Triangle Pattern of Stars
Question:
Write a Python program to print the following pattern using nested loops:
*
* *
* * *
* * * *
* * * * *
Solution:
n = 5
for i in range(1, n+1):
for j in range(1, i+1):
print("*", end=" ")
print()
Example 3: Inverted Right-Angled Triangle of Numbers
Question:
Write a Python program to print the following inverted triangle pattern:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Solution:
n = 5
for i in range(n, 0, -1):
for j in range(1, i+1):
print(j, end=" ")
print()
0 Comments
Please do note create link post in comment section