Recursion and computational thinking · A level · OCR H446 2.2.1, AQA 7517 4.1.1.16, Eduqas A500QS 1.3 · about 25 min
Base case and general case, winding and unwinding, and a spiral the robot draws by calling itself.
[1 mark]What is the base case of a recursive subroutine?
[1 mark]What does this program print?
def f(n):
if n == 0:
return 0
return n + f(n - 1)
print(f(4))[1 mark]What does this program print?
def show(n):
if n > 0:
show(n - 1)
print(n)
show(3)[1 mark]def count(n): return n * count(n - 1). What happens when count(3) is called?
[1 mark]factorial(n) returns 1 if n == 0, otherwise n * factorial(n - 1). How many calls of factorial are made in total when the main program calls factorial(4)?
[1 mark]Put the events of factorial(2) in the order they happen.
Number the lines 1 to 5 to put them in the right order.
factorial(1) returns 1factorial(0) returns 1factorial(1) calls factorial(0)factorial(2) calls factorial(1)factorial(2) returns 2Write a recursive procedure echo(n), where n is a whole number from 0 upwards:
- if n is 0 (the base case), print base and play tone(200, 0.2);
- otherwise print down <n> and play tone(200 + 100 * n, 0.2), then call echo(n - 1), then print up <n> and play tone(200 + 100 * n, 0.2) again.
Call echo(3). The output must be down 3, down 2, down 1, base, up 1, up 2, up 3, one per line, and you will hear the notes fall and rise again. Use no loops.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
def echo(n):
print("down", n)
echo(3)Plan your program here, then type it in and press Run.
sum_to(4) on paper as a table like the factorial one. How many frames are on the stack at its deepest?power(base, exp) for whole-number exp of 0 or more. What is its base case?print in spiral to after the recursive call. Predict the output before you run it.