Program for Fibonacci number in C - Codzify.com

1 min 36 sec Basic


Program for Fibonacci number in C
The Fibonacci numbers are the numbers in the following integer sequence.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

There are various methods to execute the Fibonacci number program using recursion, using dynamic programming, using space optimised method etc.

In this tutorial, we are going to cover two of the most common methods to run the Fibonacci series.

  1. Using Recursion
  2. Using Space optimized method
#include 
void fib(int n, int a, int b)
{ 
  int result;
  result = a + b; 
  printf(",%d", result);
 a = b;  
  b = result; 
  
if(n > 0)
{
 fib(n - 1, a, b); 
}
}

 int main() 
 {
      int a = 0, b = 1;
      printf("0,1");
     fib(8 , a,b);
      return 0;
}

Output

0,1,1,2,3,5,8,13,21,34,55

2) Using Space Optimised method

  
#include
int fib(int n)
{
  int a = 0, b = 1, c, i;
  if( n == 0)
  {
    return a;
 }
  for (i = 2; i <= n; i++)
  {
     c = a + b;
     a = b;
     b = c;
  printf("%d, ",a);
  }
  return b;
}
 
int main ()
{
  int n = 8;
    printf("0, ");
    fib(n);
  return 0;
}

Output

0, 1, 1, 2, 3, 5, 8, 13,

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python