DimitrisPax
DimitrisPax

Reputation: 25

Why is needed here to have if statements in the function in order to work?

When I tried to implement fibonacci sequence using recursion in C, I noticed that in my function fibo if I didn't use some kind of if statements that return 1 out of the function the program crashed.Why did this happens?

#include<stdio.h>

int fibo(int);
int main(void){
    int n, num;

    scanf("%d", &n);

    num = fibo(n);
    printf("apo: %d", num);
    return 0;
}


int fibo(int n){
    if(n==0)
        return 0;
    else if(n==1)
        return 1;
    else if(n!=0){
        n = fibo(n-1) + fibo(n-2);
    return n;
    }
}


/*FOR EXAMPLE if I leave the fuction like this, it doesn't work*/
int fibo(int n){
        n = fibo(n-1) + fibo(n-2);
    return n;
}

Upvotes: 1

Views: 56

Answers (2)

klutt
klutt

Reputation: 31439

Let's take the absolute simplest case of a recursive function.

int foo(int n) 
{ 
    return foo(n-1); 
}

If you want to calculate foo(5) then the function foo will need to calculate foo(4) before returning. But same goes for foo(4). It has to calculate foo(3) first. So there is no value for n where the function does not need to call itself, thus recursing indefinitely. In theory that is. In practice it will crash.

Those cases that does not cause a recursive call are called base cases.

Upvotes: 3

yupe
yupe

Reputation: 127

Your function needs a limit(base case) to no longer to execute itself, If you don't have the statement "if" to decide when to jump out of the function, your following program can't be executed. and the function won't stop execute until your program collapses.

Upvotes: 1

Related Questions