Lompat ke konten

Lesson 83: Recursion

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.

Masuk atau buat akun

IGCSE, A-Level & AP