0
int fib(int i) {
    if(i<2) {
        return 1;
    }
    else {
        return fib(i-1) + fib(i-2) ;
    }
}

I am not able to understand how the statements return fib(i-1) + fib(i-2) is processed???

Does fib(i-1) is process first and fib(i-2) or both get processed simultaneously??

Also, suppose fib(i-1)=3, then in this case how fib(i-1)=3 gets calculated..i know that this further get called to fib(i-1)=2 and fib(i-1)=1 which give 1 as return in both cases. Then how does fib(i-1)=3 gets calculated based on fib(i-1)=2 and fib(i-1)=1???

Hülya
  • 3,353
  • 2
  • 12
  • 19
waqas
  • 1
  • 1

3 Answers3

0

Something along the lines of:

fib(4) = 
fib(3) + fib(2) = 
fib(2) + fib(1) + fib(2) = 
fib(1) + fib(0) + fib(1) + fib(2) = 
1 + fib(0) + fib(1) + fib(2) = 
1 + 1 + fib(1) + fib(2) = 
2 + fib(1) + fib(2) = 
2 + 1 + fib(2) = 
3 + fib(2) = 
3 + fib(1) + fib(0) = 
3 + 1 + fib(0) = 
4 + fib(0) = 
4 + 1 = 
5

Nothing gets exectued "simultaneously", it just calls fib multiple times in itself while evaluting your first call of fib(4).

luk2302
  • 55,258
  • 23
  • 97
  • 137
0

Each time it runs into the statement return fib(i-1) + fib(i-2) ;, it must find out what fib(i-1) is first and then what fib(i-2) is each time. Every time where i does not fulfill the requirement of being less than 2, it must go to an instance of return fib(i-1) + fib(i-2) ;. It then looks first for what that fib(i-1) is and then what that fib(i-2) is. If fib(i-1) is what caused it to go to another instance of the else statement, then that means it will be looking for the second fib(i-1) and then the second fib(i-2) before looking for the first fib(i-2) since those second parts are needed to determine what the first fib(i-1) is. It will continue to go deeper and further with the else statement as long as it does not meet the if statements requirements. Once, it has its first 1 from the if statement, it will then be able to start filling in all the values for the fib(i-1)s and fib(i-2)s it previously ran into until it gets back to the first fib(i-1). Only then can it move on to the first fib(i-2) and go down as it needs to there to enter the if statment before entering in those 1s and adding them up to find just what the first return fib(i-1) + fib(i-2) ; is. If this only makes things more confusing, I would recommend writing it out with arrows pointing to show the steps being taken so you know where you are and what all has been done more clearly. Doing that helped me out when first learning recursion with Fibonacci.

-1
fib(4) =                fib(3)                +                   fib(2)

                fib(2)        +       fib(1)     +           fib(1)    +     fib(0)

            fib(1) + fib(0)   +         1        +             1       +       1

              1   +   1       +         1        +             1       +       1     =    5
Gnk
  • 645
  • 4
  • 11