code-8
code-8

Reputation: 58810

Recursive Fibonacci in C - plain simple

I'm trying write a recursive fibonacci() in c

I have

#include <stdio.h>

int fibonacci(int);

int main(int argc, char *argv[]){

   int option;
   printf("1- Calculate Fibonacci\n");
   printf("2- Exit\n");
   scanf("%d", &option);

   if(option == 1){

     int limit;
     printf("Enter and integer: ");
     scanf("%d", &limit);

     printf("The Fibonacci sequence is : \n");

     fibonacci(limit);

    }else if(option == 2){
        return 0;
    }else{
        printf("Please select your option :  1 or 2.\n");
    }

    return 0;
}


int fibonacci(int n){

   if ( n == 0 )
      return 0;
   else if ( n == 1 )
      return 1;
   else
      return ( fibonacci(n-1) + fibonacci(n-2) );
}

After compile, and run I got

./a.out 
1- Calculate Fibonacci
2- Exit
1
Enter and integer: 5
The Fibonacci sequence is : 

I never get my number printing out.

Any hints on what I forgot ?

Upvotes: 1

Views: 670

Answers (4)

Mihai
Mihai

Reputation: 42

Replace:

printf("The Fibonacci sequence is : \n");

fibonacci(limit);

with

printf("The Fibonacci sequence is : %d \n",fibonacci(limit));

or

int result;
result = fibonacci(limit);
printf("The Fibonacci sequence is : %d \n",result);

Upvotes: 3

Bidisha Pyne
Bidisha Pyne

Reputation: 541

fibonacci(limit);

This line is not printing anything, you return your answer in some result in some variable or print it simply by printf("%d", fibonacci(limit));

Upvotes: 0

Will_Panda
Will_Panda

Reputation: 534

You don't print anything in fibonacci(int) method.

Upvotes: 2

Idos
Idos

Reputation: 15320

fibonacci(limit); does not print anything even though your code theoretically "works".

Upvotes: 3

Related Questions