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).
คลิก Run เพื่อดูผลลัพธ์ที่นี่
ความยาก 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) และ fib(10) need.
คลิก Run เพื่อดูผลลัพธ์ที่นี่