Algorithms · GCSE · OCR J277 2.1.2, AQA 8525 3.1.1, Edexcel 1CP2 1.2.4 · about 15 min
Following an algorithm line by line, and tracing to find a logic error.
[1 mark]What does this program print?
total = 0
for i in range(1, 5):
total = total + i * 2
print(total)[1 mark]What does this program print?
x = 1
y = 10
while x < y:
x = x * 2
y = y - 1
print(x, y)[1 mark]A program prints the average of five readings as 4.0 when it should be 30.0. A trace shows total goes 40, 35, 30, 25, 20. What is the bug?
[1 mark]What is a trace table used for?
[1 mark]What does this program print?
n = 20
steps = 0
while n > 1:
n = n // 2
steps = steps + 1
print(n, steps)Fix the average program so it prints average: 30.0. Keep a trace: inside the loop, print a line i=<i> total=<total> each time round, so the program shows its own trace table.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
readings = [40, 35, 30, 25, 20]
for i in range(len(readings)):
total = 0
total = total + readings[i]
print("average:", total / len(readings))Plan your program here, then type it in and press Run.
n = 27 then while n != 1: if n is even, n = n // 2, else n = 3 * n + 1 for the first six rows. Then run it to see how long it really takes.x and y loop above. Trace it again before running. Does it still stop?