Problem: Write a C program to print the Fibonacci series up to n terms.

What is Fibonacci Series?

In mathematics, the Fibonacci numbers commonly denoted Fₙ, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1.

Wikipedia

In the Fibonacci series, the first and second terms are 0 and 1 respectively, and every nth term is the sum of (n-2)th term and (n-1)th term.

Example: 0, 1, 1, 2, 3, 5, 8, 13 ,etc.

Print Fibonacci Series in C using Loop

Steps to print the Fibonacci Series in C:

  1. Initialize a=0 as first and b=1 as the second term.
  2. Calculate the next term c using the formula a+b.
  3. Output c and update a=b and b=c.
  4. Repeat again from step 2 till the nth term.

we have to implement step-2 and step-3 inside the ‘for’ loop for the nth term greater than 2.

For n=1 we output the value of a and for of n=2 we output both a and b.

Here is the implementation of the steps in C:

#include <stdio.h>
 
int main(void) {
  int n, a=0, b=1, c;
 
  printf("Enter the number of terms \n");
  scanf("%d",&n);
 
  if(n==1){
    printf("%d", a);
  } else if(n == 2){
    printf("%d %d", a, b);
  } else {
    printf("%d %d ", a, b);
    
    for(int i=3; i<=n; i++){
      c=a+b;
      a=b;
      b=c;
      printf("%d ", c);
    }
 
  }
  return 0;
}

Output

Enter the number of terms
10
0 1 1 2 3 5 8 13 21 34

Print Fibonacci Series in C using Recursion

Fibonacci series can also be implemented using recursion.

The recursion method will return the nth term by computing the recursive(n-2)+recursive(n-1).

Since the recursive method only returns a single nth term we will use a loop to output each term of the series.

#include <stdio.h>
 
int main(void) {
  int n, a=0, b=1, c;
 
  printf("Enter the number of terms \n");
  scanf("%d",&n);
 
  if(n==1){
    printf("%d", a);
  } else if(n == 2){
    printf("%d %d", a, b);
  } else {
    printf("%d %d ", a, b);
    for(int i=3; i<=n; i++){
      printf("%d ", nthRecursiveTerm(i));
    }
  }
  return 0;
}
 
//Recursive function
int nthRecursiveTerm(int n){
  if(n==1)
    return 0;
  else if(n==2)
    return 1;
  return nthRecursiveTerm(n-2)+nthRecursiveTerm(n-1);
}

Output

Enter the number of terms
10
0 1 1 2 3 5 8 13 21 34

In this tutorial, we learned to print the Fibonacci series in c programming language.

Leave a Reply