CBSE Class 11 Computer Science Question 44 of 80

Conditional and Looping Constructs — Question 14

Back to all questions
14
Question

Question 9

Write the output of the following code:

for i in range (2) :
  for j in range (1) :
   if i+2 == j:
      print ("+",end=" ") 
   else:
      print ("o",end=" ")
Answer
Output
o o
Explanation

Let’s break down the code step-by-step:

  1. Outer Loop: for i in range(2): → This loop iterates over the range of numbers starting from 0 up to but not including 2. So, i will take on the values: 0, 1.

  2. Inner Loop: for j in range(1): → For each value of i in the outer loop, j will iterate over the range of numbers starting from 0 up to but not including 1. So, j will take on the only value: 0.

  3. if i + 2 == j: → This condition checks if i + 2 is equal to j.

  4. print("+", end=" ") → If the condition i + 2 == j is true, this statement prints a "+", followed by a space, without moving to a new line.

  5. print("o", end=" ") → If the condition i + 2 == j is false, this statement prints an "o", followed by a space, without moving to a new line.

Let’s analyze the loops iteration by iteration:

  • First iteration of the outer loop (i = 0):
    • Inner loop (j = 0):
      • i + 2 == j becomes 0 + 2 == 0, which is 2 == 0, is false.
      • Therefore, the else block is executed, and the output is o
  • Second iteration of the outer loop (i = 1):
    • Inner loop (j = 0):
      • i + 2 == j becomes 1 + 2 == 0, which is 3 == 0, is false.
      • Therefore, the else block is executed, and the output is o

So, combining the outputs of all iterations, the full output will be:

o o 

Each "o" is followed by a space, and there is no new line between them due to the end=" " parameter in the print function.