Fibonnaci Series

Updated : Jun 21, 2014 in C Programming

Fibonacci series in C using for loop and Recursion

This is my first post on this blog so i thought i should start with easy one. While learning i am 100% sure that everybody might have done this Fibonacci series in different programming language. C is my first programming language and also it’s very easy to understand for any beginner so i will explain this problem using C.Fionacci Series

What is Fibonacci Series ?

In mathematics, the Fibonacci numbers or Fibonacci sequence are the numbers in the following integer sequence

1,1,2,3,5,8,13,21,34,55,89,144,.....

or

0,1,1,2,3,5,8,13,21,34,55,89,144,.....

By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.

For example 13 is sum of previous two numbers 8 and 5 and so on. So i will not waste you time and share the code.

Fibonacci series in C programming using for loop

/* Fibonacci series in c programming using for loop */
#include<stdio.h>
 
int main()
{
   int n, first = 0, second = 1, next, c;
 
   printf("Enter the number of terms\n");
   scanf("%d",&n);
 
   printf("First %d terms of Fibonacci series are :-\n",n);
 
   for ( c = 0 ; c < n ; c++ )
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = first + second;
         first = second;
         second = next;
      }
      printf("%d\n",next);
   }
 
   return 0;
}

Fibonacci series in C programming using Recursion

/* Fibonacci series program in c using recursion */
#include<stdio.h>
 
int Fibonacci(int);
 
main()
{
   int n, i = 0, c;
 
   scanf("%d",&n);
 
   printf("Fibonacci series\n");
 
   for ( c = 1 ; c <= n ; c++ )
   {
      printf("%d\n", 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) );
}

Note : Recursive method uses stack , so if you are calculating series for large number frequently, may be you will get stack overflow error.

Please let me know your idea suggestion in the comment.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *