Become Our Fan on Social Sites!

Facebook Twitter

Google+ RSS YouTube

Wednesday, 18 September 2013

Fibonacci Series using for loop and recursion

Following are different versions of fibonacci series program. First program uses looping structure and second program uses recursion.


1) Using for loop
 
#include<stdio.h>
 
int main()
{
   int first = 0, second = 1, next, c, no;
 
   printf("Enter the number of terms : ");
   scanf("%d",&no);
 
   for( c = 0 ; c < no ; c++ ) {
      if ( c <= 1 )
         next = c;
      else {
         next = first + second;
         first = second;
         second = next;
      }
      printf("%d ",next);
   }
   return 0;
}
 
 
2) Using Recursion 

#include<stdio.h>

int Fibonacci(int);

int main()
{
    int no, i = 0, c;
    scanf("%d",&no);

     for( c = 1 ; c <= no ; c++ )
       {
        printf("%d ", Fibonacci(i));
        i++;
       }
    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) );
}

0 comments :

Post a Comment