Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Fibonacci Series using recursion C Programming

August 25, 2013 Posted by: GPA Views: 1449 0 comments

Problem

Find Fibonacci Series using recursion

Solution

The Fibonacci series 0, 1, 1, 2, 3, 5, 8, 13..., Fibonacci number is the sum of the previous two Fibonacci numbers.

The Fibonacci series may be calculated recursively as follows: 

fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n – 1) + fibonacci(n – 2) 

Each time fibonacci function is called, it tests for the base case—n is equal to 0 or 1. If this is true, n is returned, if n is greater than 1, the recursion step generates two recursive calls, each of which is for a simpler problem than the original call to fibonacci.

 

Example:

   

#include <stdio.h>
#include <stdlib.h>
long fibonacci(long inputnumber); // function prototype
int main(int argc, char *argv[])
{
   long inputnumber;//number input by user
   printf( "Enter an integer: " );//prompt user to enter number
   scanf( "%ld", &inputnumber );
   //show result
printf( "Fibonacci(%ld) = %ld\n", inputnumber, fibonacci(inputnumber) );
   system("PAUSE");
   return 0;
}
//Recursive definition of function fibonacci
long fibonacci( long inputnumber ){
   if (inputnumber == 0 || inputnumber == 1 ) {
      return inputnumber;
   }else {
     return fibonacci(inputnumber - 1 ) + fibonacci( inputnumber - 2 );// recursive step
   }
}

Output

Fibonacci Series using recursion C

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe