Trace the following code and state its exact output.
for i in range(1, 4):
line = ""
for j in range(i):
line = line + str(i)
print(line)
Show the markscheme
Markscheme (3 marks)
- First line: 1.
- Second line: 22.
- Third line: 333 (and there are no more lines:
range(1, 4)does not include 4). - Trace table showing
linereset to""for eachiand the inner loop runningitimes (jfrom 0 toi - 1).
A full-marks answer
One row per change of a variable or output:
i j line output
1 ""
1 0 "1"
1 1
2 ""
2 0 "2"
2 1 "22"
2 22
3 ""
3 0 "3"
3 1 "33"
3 2 "333"
3 333line is reset to "" on each iteration of the outer loop and the inner loop runs i times. Exact output, on three lines: 1, 22, 333.
Trace the following code and state its exact output.
for (int i = 1; i < 4; i++) {
String line = "";
for (int j = 0; j < i; j++) {
line = line + i;
}
System.out.println(line);
}
Show the markscheme
Markscheme (3 marks)
- First line: 1.
- Second line: 22.
- Third line: 333 (and there are no more lines:
i < 4is false whenireaches 4). - Trace table showing
linereset to""for eachiand the inner loop runningitimes (jfrom 0 toi - 1).
A full-marks answer
One row per change of a variable or output:
i j line output
1 ""
1 0 "1"
1 1
2 ""
2 0 "2"
2 1 "22"
2 22
3 ""
3 0 "3"
3 1 "33"
3 2 "333"
3 333line is declared again as "" on each iteration of the outer loop and the inner loop runs i times. Exact output, on three lines: 1, 22, 333.