Program for Fibonacci series in C which is implemented using a different method in c.
What is Fibonacci series: Fibonacci is a series of numbers starting from 0 and adding with two numbers before it.

Fibonacci series is a collection or set of the numbers starting with zero or one, followed by the sum of two preceding numbers.
Consider Fibonacci series till N which is implemented as 0,1,(0+1),(0+2)…. N.
Example : Write Fibonacci series up to 8 numbers.
0,1,1,2,3,5,8,13.
We calculated this series as first two number as 0 and 1 , 0+1 => 1, 1+2=>3 ,3+2=>5,5+3=>8,8+5=>13

Algorithm for Fibonacci series

  1. Initialize the variables, a=0, b=1, and temp = 0
  2. Input number of terms of Fibonacci series to be printed
  3. Print First two terms of series
  4. Use loop for the following steps
    temp =a+b
    a=b
    b=temp
    increase value of i each time by 1
  5. print the value of temp

Fibonacci series flowchart

Fibonacci series flowchart
Fibonacci series flowchart

We implement the Fibonacci series in c in two ways as

  1. Fibonacci series using for Loop
  2. Fibonacci series using While Loop
  3. Fibonacci series using recursion

Fibonacci series using for Loop

This is the first method to print the Fibonacci series. In this, we use the for loop to iterate number to range up to which we want to print the Fibonacci series.

Program for Fibonacci series using for loop

#include <stdio.h>
int main()
{
int i, n, t1 = 0, t2 = 1, nextTerm;

printf("Input the number of terms for Fibonacci Series: ");
scanf("%d", &n);

printf("\nFibonacci Series is as follows ");

for (i = 1; i <= n; ++i)
{
printf("%d, ", t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

Output :

fibonacci series program in c

Fibonacci series using while Loop

This is the second method to print the Fibonacci series. In this, we use the while loop to iterate number to range up to which we want to print the Fibonacci series.

C program for Fibonacci Series using while loop

#include<stdio.h>
int main()
{
int n,i,a,b,c;
printf("Input the number of terms for Fibonacci Series:");
scanf("%d",&n); 
printf("\nFibonnaci Series is as follows\n");
i=1;
a=0;
b=1;
while(i<=n)
{
printf("%d ",a);
c = a + b;
a = b;
b = c;
i++;
}
return 0;
}

Output :

fibonacci series program in c

Fibonacci Series using recursion

In this, we recursively call the function calculating the series to range up to which we want to print the Fibonacci series.
Recursion in c: It is a process where function calls itself directly or indirectly.

C program for Fibonacci Series using recursion

#include<stdio.h>

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

int main()
{
int n,i=0;
printf("Input the number of terms for Fibonacci Series:");
scanf("%d",&n);
printf("\nFibonnaci Series is as follows\n");
while(i<n)
{
printf("%d ",fibonacci(i));
i++;
}

return 0;
}

Output :

fibonacci series program in c

Write A Comment