CrazyEngineers
  • Doubt in c program

    krishbcs

    krishbcs

    @krishbcs-5tG26c
    Updated: Oct 27, 2024
    Views: 1.0K
    how work this recursive function. would any one of you Explain this? please...

    int Fib(int N)
    {
    if(int N)
    return 1;
    else
    return Fib(N-1)+Fib(N-2);
    }
    0
    Replies
Howdy guest!
Dear guest, you must be logged-in to participate on CrazyEngineers. We would love to have you as a member of our community. Consider creating an account or login.
Replies
  • nareshkumar6539

    MemberMar 29, 2012

    Recursion: calling a function from it self is called Recursion
    In if clause you need to check the condition like N==0 ||N==1 .
    for understanding purpose divide that code into steps
    Step1:check if condition and return value
    Step2:else block.again divide step 2 into parts
    2.1:Fib(N-1)
    2.2: Fib(N-2)
    2.3:return Fib(N-1)+Fib(N-2)[means add step 2.1 and 2.2 and return the value]
    Take N=3 call Fib(3) it will check the if condition not true so control will go to else block[Step 2]
    in that first it will execute 2.1 step i.e call Fib(2) in this case also it will perform the above steps[checking 1 & 2 Steps] after return the value, it will execute 2.2 step i.e Fib(1) in this also it will check all the steps after return the value, 2.3 step executed i.e return value of Fib(2)+Fib(1).
    in the above example Fib(3) calling Fib(2) and Fib(1) from its function itself this shows recursion.
    Are you sure? This action cannot be undone.
    Cancel
  • Anoop Kumar

    MemberMar 29, 2012

    what is the problem?
    its program for Fibonacci series!!! 0, 1, 1, 2, 3, 5, 8... and so on.
    there should be check that number should not be less than 0.
    Are you sure? This action cannot be undone.
    Cancel
  • rahul69

    MemberApr 9, 2012

    This is a messed up program as the if condition is not proper.
    'if(int N)' should be an error.
    It should be replaced by if(N<=2) to get proper result as the logic is written that way.
    The recursion happens in following manner😔eg: N=3)
    fib(3)
    fib(2) + fib(1)
    1 + 1 =2
    as 3rd term is 2 (1,1,2,...) and so on..
    Are you sure? This action cannot be undone.
    Cancel
Home Channels Search Login Register