Lesson 83: Recursion
此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
A function that calls itself
- Recursion: a function is defined in terms of itself, so it calls itself.
- It needs a base case, which returns an answer without calling itself, and a general case, which calls itself with a smaller problem.
- Without a base case the calls never stop, and the board runs out of memory for them.
| Call | Gives |
|---|---|
| fib(1) | 1 (base case) |
| fib(0) | 0 (base case) |
| fib(2) | fib(1) + fib(0) = 1 |
| fib(3) | fib(2) + fib(1) = 2 |
| fib(4) | fib(3) + fib(2) = 3 |
- Robots lesson 27 (Fractal tree) and lesson 81 (in-order traversal) also use recursion.
English
In the exam
- 9618/31/M/J/23 Q12: (a) describe recursion. Mark scheme: a function or procedure defined in terms of itself / that calls itself; it must have a base case, a way to return without a recursive call; and a general case where the recursive call takes place. (b) Trace the recursive function Fib, which uses the same IF Number <= 1 THEN base case as your program, for Fib(5). The marks cover the calls going down to the base case (winding) and the results coming back (unwinding).
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
In the Fibonacci sequence each number is the sum of the two before it: 0, 1, 1, 2, 3, … Write fib as a recursive function, like the exam's: if number is 0 or 1, return number (the base case); otherwise return fib(number - 1) + fib(number - 2) (the general case). The program prints fib(0) to fib(10).
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
How much work is it? Add 1 to calls at the start of every call of fib. The program then prints how many calls fib(5) and fib(10) need.
点击“运行”查看此处输出。