CBSE Class 11 Informatics Practices Question 49 of 75

Conditional and Looping Constructs — Question 21

Back to all questions
21
Question

Question 7(d)

Write the output of the following:

for x in range (1, 6) :
   for y in range (1, x+1):
      print (x, ' ', y)
Answer
Output
1   1
2   1
2   2
3   1
3   2
3   3
4   1
4   2
4   3
4   4
5   1
5   2
5   3
5   4
5   5
Explanation

Below is the detailed explanation of this code:

1. Outer Loop: for x in range(1, 6):

  • This loop iterates over the range of numbers starting from 1 up to but not including 6. So, x will take on the values: 1, 2, 3, 4, 5.

2. Inner Loop: for y in range(1, x + 1):

  • For each value of x in the outer loop, y will iterate over the range of numbers starting from 1 up to and including x (since x + 1 is exclusive).

3. print(x, ' ', y)

  • This prints the current values of x and y separated by a space.

Let’s analyze the loops iteration by iteration.

Outer loop (x values ranging from 1 to 5):

When x = 1:

  • The inner loop range(1, 2) results in y taking values: 1.
  • Output:
    1   1
    

When x = 2:

  • The inner loop range(1, 3) results in y taking values: 1, 2.
  • Output:
    2   1
    2   2
    

When x = 3:

  • The inner loop range(1, 4) results in y taking values: 1, 2, 3.
  • Output:
    3   1
    3   2
    3   3
    

When x = 4:

  • The inner loop range(1, 5) results in y taking values: 1, 2, 3, 4.
  • Output:
    4   1
    4   2
    4   3
    4   4
    

When x = 5:

  • The inner loop range(1, 6) results in y taking values: 1, 2, 3, 4, 5.
  • Output:
    5   1
    5   2
    5   3
    5   4
    5   5
    

Putting all these outputs together, we get:

1   1
2   1
2   2
3   1
3   2
3   3
4   1
4   2
4   3
4   4
5   1
5   2
5   3
5   4
5   5