In this lecture, I want to show you what is
a recursion.
There is a quote, which says: To understand
recursion, you must first understand recursion.
It's okay if you don't get it now, I hope
you'll at the end of the video.
Recursion is when you write a function and
it calls itself.
Let's debug to see what's happening.
Every time a program calls itself, it added
to the call stack.
If I remove the debug point and let the program
run we will get a stack overflow exception.
A stack overflow occurs if the call stack
pointer exceeds the stack bound and it happens
because our function doesn't have any exit
point.
So let's create one.
I initialized a counter variable and made
a condition that checks if the counter is
equal to zero, then exit the function and
I decreased the counter variable as well.
If we run this, first we call the recursion
function from the main method, then the recursion
function calls itself and return because the
counter is 0, so the first call will continue
from line twenty two.
You can see that the exit point works well
and we don't get exception anymore.
Now let's see a real life example with the
help of Fibonacci sequence.
Fibonacci sequence is a series of numbers,
where the first and the second number are
given, which is 1 and 1.
We calculate the next number by adding up
the two numbers before it.
Thus, the third number will be 2, because
the previous two were 1 and 1
The fourth number will be 3, because the previous
two were 2 and 1 and so on.
Now let's see the recursive implementation
of the Fibonacci numbers.
If N is equal or less than 1, then we return
with 1, and in every other case we call this
method with n-1 + n-2
If we run the code, we can be sure it works
well, because the 3rd element is two, the
4th is 3 and the fifth is 5
But why does it work?
Here is a simple explanation that may help
you to understand.
Let's say we call the Fibonacci function with
4, so now N is equal to 4.
Because 4 is not less or equal than 1, then
it will return with sum of N-1 and N-2 which
is Fib three and Fib 2
Now expand the Fib three on the left side
Fib 3 will return with Fib 2 + Fib 1, and
as you can see, the exit point was met with
fib 1, and it returns with 1.
Now expand Fib2 on the left side.
Fib2 will call Fib1, which returns with 1,
and Fib 0 which returns with 0
Because we said, that we will return the sum
of the values, Fib 2 will return with 1 +
0, which is 1.
Now we can return to fib3 with fib2 and fib1,
the value of fib3 will be 1 + 1, which is
2
Finally we expand the right side.
So, fib 2 will call fib1 and fib 0, and it
will return with 1 + 0, which is 1
SO now expand Fib 4.
Fib 4 will be the sum of Fib3 and fib2 which
is 2 + 1, so fib4 will return with 3, and
that’s how our algorithm ends.
I hope now you understand how recursion works,
I think it's not an easy topic, but there
are plenty of tasks on the internet that you
can practice with.
If you liked the video, don't forget to hit
the like button and subscribe.
