please exaplain this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

please exaplain this code

please explain this program to find nth fibinocci number using recursion https://www.sanfoundry.com/c-program-fibonacci-number-using-recursion/

1st Aug 2019, 7:11 AM
Sachin M
Sachin M - avatar
1 Answer
+ 1
Okay, going to try to help you :D. The two if statement in the fibo function are your ways out of the recursive loop. Those are here because when you do recursion, you need to be able to go away of the recursion by stopping function call, so when num will be less or equal than 1, we will return num instead of function calls. The last if statement will return the sum of fibo(num - 1) + fibo(num - 2). Here it's a little harder, the function fibo will call fibo(num - 1) first, and will only call fibo(num-2) when fibo(num-1) have return something. So for num = 4, for example, the function will go: fibo(4) = fibo(3) + fibo(2) fibo(4) will first call fibo(3) fibo(3) = fibo(2) + fibo(1) Here fibo(3) will first call fibo(2) fibo(2) = fibo(1) + fibo(0) As we know when num <= 1 it returns a number so fibo(1) is actually 1 and fibo(0) is 0 fibo(2) = 1 + 0 = 1 Now that fibo(2) has called all of its two return function and those have returns values, fibo(2) returns the sum of both the values. So our first fibo(3) is now equal to fibo(3) = 1 (this is the result of fibo(2) after the recursion) + fibo(1) It will now call fibo(1) which is equal to 1 as we know fibo(3) = 1 + 1 = 2 Know that fibo(3) has called fibo(2) and fibo(1), it returns their sum, which is 2 So fibo(4) now looks like this fibo(4) = 2 + fibo(2) fibo(4) will now call fibo(2), which will call its own two fibo functions, but we already know that fibo(2) = 1, so fibo(4) = 2 + 1 = 3 Now that fibo(4) has completed all of its function call, it will return the sum of both the result it receives There you go, hoping I was clear, if not, sorry ^^'
1st Aug 2019, 8:30 AM
Thomas Teixeira
Thomas Teixeira - avatar