Lesson 83: Recursion
Halaman ini memerlukan browser terbaru (dengan dukungan SharedArrayBuffer). Silakan perbarui Chrome, Edge, Firefox, atau Safari ke versi terbaru.
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).
Kesulitan 4/5 · 280 koin + bonus kecil pada penyelesaian pertama hari ini
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).
Klik Jalankan untuk melihat output di sini.
Kesulitan 3/5 · 200 koin + bonus kecil pada penyelesaian pertama hari ini
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) dan fib(10) need.
Klik Jalankan untuk melihat output di sini.