30 lines
1.6 KiB
HTML
30 lines
1.6 KiB
HTML
|
<p>
|
||
|
Recursion means, that something defines itself by itself.
|
||
|
In maths series like factorial or the Fibonacci series are often defined recursively.
|
||
|
You can also have data structures, which are define recursively. Like trees.
|
||
|
What we want to do now, is to define a recursive function.
|
||
|
A function, that calls itself.
|
||
|
</p>
|
||
|
<p>
|
||
|
This is useful, because it is often shorter and more easily to understand than the iterative version.
|
||
|
In some cases you only can use recursion.
|
||
|
</p>
|
||
|
<p>
|
||
|
This is also a good time to talk about the stack. The stack is the place, were all your local data lives.
|
||
|
You can imagine it as just a big pile of documents.
|
||
|
You can only put stuff on the top or grab something from the top.
|
||
|
This is called push and pop in computer science.
|
||
|
</p>
|
||
|
<p>
|
||
|
So all your local variables and function arguments get pushed on the stack.
|
||
|
When a function ends, the whole block, which belonged to the function (the so called stack frame),
|
||
|
gets popped. The only problem is, that the stack has a limited size. So if you have a a recursive function,
|
||
|
that just keeps calling itself, you will run out of memory on the stack. This is called a stack overflow.
|
||
|
Fortunately memory is cheap these days. So it is not that big of a problem anymore.
|
||
|
</p>
|
||
|
<p>
|
||
|
Your task is to write a recursive function, which returns the nth number of the Fibonacci sequence.
|
||
|
The Fibonacci numbers are a sequence of numbers where each is the sum of both it's predecessors.</p>
|
||
|
<p>When:<br>fib(0) = 0 and fib(1) = 1<br>Then:<br>fib(2) = 1<br>fib(3) = 2</p>
|
||
|
<p>We get the following sequence: 0, 1, 1, 2, 3, 5... </p>
|