Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tracing recursion for fibonacci series [closed]

Tags:

c

recursion

I am trying to understand the recursion mechanism used for fibonacci series.

#include<stdio.h>
int fib(int n);
int main()
{
    int x, n;
    scanf("%d", &n);
    x = fib(n);
    printf("fibonacci number %d = %d\n", n, x);
    return 0;
}
int fib(int n)
{
    if (n == 0)
    {
        return 0;
    }
    else if (n == 1)
    {
        return 1;
    }
    else
    {
        return (fib(n -1) + fib(n - 2));
    }
}

Above is the code for the series. I can trace the program(for n=6) till the point where the first term in the return calls fib(1) and then returns 1. After that, I am kinda lost in tracing the execution. I have tried to understand it through stack diagrams but I am still confused. Can anybody help me with this? Also how can I trace the stack frame using gdb and see the variable values on stack frames?

Thanks

like image 665
Vaibhav Sundriyal Avatar asked Jan 02 '14 00:01

Vaibhav Sundriyal


People also ask

Can we print Fibonacci series using recursion?

It adds previous two numbers value to compute the next number value. In this program fibonacci series is calculated using recursion, with seed as 0 and 1. Recursion means a function calling itself, in the below code fibonacci function calls itself with a lesser value several times.

How do you find Fibonacci without recursion?

The logic of calculating nth Fibonacci number is implemented in this method and it does that without using recursion. It uses a simple for loop to iterate until the nth number and calculate Fibonacci number using the following formula : f(n) = f(n-1) + f(n-2);

What kind of recursion is Fibonacci?

Tail Recursion for Fibonacci - GeeksforGeeks.


2 Answers

think of some random number and draw steps of execution(like a tree). i'd always use pen and paper to understand algorithm stuff. and also, always try to break down the whole program to each tiny logic and make sure you understand each one of them. I drew this diagram for you.i'm sorry for being such a horrible artist. enter image description here

like image 92
CoderKK Avatar answered Oct 03 '22 13:10

CoderKK


To understand this, I renamed your fib fnction to fibonacci. Now suppose user enters 3 then the recursive call can be understand as (> is for call and < is for return):

> fibonacci(3)
|   > fibonacci(2)
|   |   > fibonacci(1)
|   |   < 1
|   |   > fibonacci(0)
|   |   < 0
|   < 1
|   > fibonacci(1)
|   < 1
< 2

Which can be understand more in a more clear way by block diagram1.

enter image description here


1. Taken from C how to program by Deitel.

like image 21
haccks Avatar answered Oct 03 '22 15:10

haccks