Class xi nested loop with questions

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
# Number of rows n = 5 # Outer loop for each row for i in range(1, n+1): # Inner loop to print numbers in each row for j in range(1, i+1): print(j, end=" ") # Move to the next line after each row 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:

# Number of rows n = 5 # Outer loop for each row for i in range(1, n+1): # Inner loop to print stars for j in range(1, i+1): print("*", end=" ") # Move to the next line after each row 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:

# Number of rows n = 5 # Outer loop for each row for i in range(n, 0, -1): # Inner loop to print numbers for j in range(1, i+1): print(j, end=" ") # Move to the next line after each row print()

Post a Comment

0 Comments