Fibonacci series in C

Fibonacci series in C

Problem Statement: Print Fibonacci Series in C

Given a number N, write a c program to print the fibonacci series up to N’th term.

What is a fibonacci series?

A series is called the Fibonacci series if each number in the series is the sum of the two previous numbers starting from 0 and 1.

That is,

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

You can see in the above series, every number is the sum of previous two numbers.

The series is commonly denoted by the mathematical formula:

T(n) = T(n-1) + T(n-2)

where, 
n > 1
T(n) is the (n+1)th term in the series
T(0) = 0, T(1) = 1

Coming back to the original problem statement, if N = 5, corresponding fibonacci series will be:

0,1,1,2,3

Similarly, if N = 10, corresponding fibonacci series will be:

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

Solution

Since we know the mathematical formula, the idea is to keep on generating every number of the series using the formula starting from the 3rd term till (N-1)th term and simultaneously print the fibonacci series.

Steps:

  • Initialise the first and second terms to 0 and 1 respectively.
  • Print first two terms
  • Run a for loop from i = 3 to N, to generate terms from 3rd term till last term of the series and print simultaneously.
    • Inside the for loop, calculate next term using the formula
    • Print the next term

C Program

// C program to print the fibonacci Series

#include <stdio.h>
int main() {

  int i, n, nextTerm;

  // initialize first and second terms
  int t1 = 0, t2 = 1;

  // get no. of terms from user
  scanf("%d", &n);

  // print the first two terms t1 and t2
  printf("Fibonacci Series: %d, %d, ", t1, t2);

  // print 3rd to nth terms
  for (i = 3; i <= n; ++i) {
    // calculate the next term
    nextTerm = t1 + t2;
    printf("%d, ", nextTerm);
    t1 = t2;
    t2 = nextTerm;
    nextTerm = t1 + t2;
  }

  return 0;
}

Output:

For N = 5,

Fibonacci Series: 0, 1, 1, 2, 3,