What will be the output of the following code:
n = 3
for i in range(n):
for j in range(n-i):
print(j+1, end="")
print()
Options:
a)123
12
1
b)321
21
1
c)123
23
3
d) None of the above
Answer:
Answer by student
a) 123
-lock-
12
1
Detailed answer by teachoo
Let’s go through each of the options and see why they are correct or incorrect.
- Option a: 123 12 1
This option is correct . The code uses a nested for loop to print the numbers from 1 to n-i in each line, where n is 3 and i is the outer loop variable. The outer loop runs from 0 to 2, and the inner loop runs from 0 to n-i-1. In each iteration of the inner loop, the value of j+1 is printed without a newline, and after the inner loop ends, a newline is printed. Here is how the output is generated:
- When i = 0, the inner loop runs from 0 to 2, and prints j+1 as 1, 2, and 3. Then a newline is printed.
- When i = 1, the inner loop runs from 0 to 1, and prints j+1 as 1 and 2. Then a newline is printed.
- When i = 2, the inner loop runs from 0 to 0, and prints j+1 as 1. Then a newline is printed.
- Option b: 321 21 1
This option is incorrect . The code does not print the numbers in reverse order in each line. To do that, we would need to change the inner loop to run from n-i-1 to -1 with a negative step of -1, and print j+1 as n-i-j.
- Option c: 123 23 3
This option is incorrect . The code does not skip the first i numbers in each line. To do that, we would need to change the inner loop to run from i to n-1, and print j+1 as j-i+1.
- Option d: None of the above
This option is incorrect . There is an option that matches the output of the code, which is option a.
So, the correct answer is option a.
-endlock-