Computer Science
What is the output of the following code?
for i in range(4):
for j in range(5):
if i + 1 == j or j + 1 == 4:
print ("+", end = ' ')
else:
print ("o", end = ' ')
print()
Answer
o + o + o o o + + o o o o + o o o o + +
Working
Outer loop executes 4 times. For each iteration of outer loop, inner loop executes 5 times. Therefore, the total number of times body of inner loop gets executed is 4 * 5 = 20. Thats why there are 20 characters in the output (leaving spaces). When the condition is true then + is printed else o is printed.
Related Questions
Predict the output of the following code fragments:
for x in range(3): for y in range(4): print (x, y, x + y)
Predict the output of the following code fragments:
c = 0 for x in range(10): for y in range(5): c += 1 print (c)
In the nested for loop code below, how many times is the condition of the if clause evaluated?
for i in range(4): for j in range(5): if i + 1 == j or j + 1 == 4: print ("+", end = ") else: print ("o", end = ") print()
Which of the following Python programs implement the control flow graph shown?
(a)
while True : n = int(input("Enter an int:")) if n == A1 : continue elif n == A2 : break else : print ("what") else: print ("ever")
(b)
while True : n = int(input("Enter an int:")) if n == A1 : continue elif n == A2 : break else : print ("what") print ("ever")
(c)
while True : n = int(input("Enter an int:")) if n == A1 : continue elif n == A2 : break print ("what") print ("ever")