Finding Nth term of a fibonacci series in C

Nth Term of Fibonacci Series 

Today in this article we will learn about how to find the Nth term of the Fibonacci series in C language.

The Fibonacci sequence is a series of numbers in which each number is the sum of the two that precede it.

Starting at 0 and 1 the sequence looks like : 
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on forever
Nth Term of Fibonacci Series

Methods Discussed

  • Iterative
  • Recursive

Note – Fibonacci Series starts at 0th term.

F(0) : 0
F(1) : 1
F(2) : 1
F(3) : 2
F(4) : 3
F(5) : 5
F(6) : 8
F(7) : 13
F(8) : 21
F(9) : 34
nth term in Fibonacci Series in C

C Code (Method 1) :-

// C Program to print the nth term in fibonacci series
// Note : Acc to fibonacci series definition
// 0th term : 0, 1st term : 1
#include

int main() {

    int a = 0, b = 1;
    int nextTerm;
    
    int n = 6;
    
    // if asked to print 0th/1st term
    // f(0) = 0 and f(1) = 1
    if (n == 0 || n == 1){
        printf("fib(%d) : %d",n, n);
        return 0;
    }

    for (int i = 2; i <= n; ++i) {
        nextTerm = a + b;
        a = b;
        b = nextTerm;
    }
    printf("fib(%d) : %d",n, nextTerm);
    
    return 0;
}

Output

fib(6) : 8

Method 2 (Recursion)

The recursive function to find the nth Fibonacci term is based on below three conditions.

  • If num == 0 then return 0. As the Fibonacci of 0th term is 0.
  • If num == 1 then return 1. As The Fibonacci of 1st term is 1.
  • If num > 1 then return fibo(num – 1) + fibo(n-2). As the Fibonacci of a term is sum of previous two terms.

Code

// C Program to print the nth term in fibonacci series
// Note : Acc to fibonacci series definition
// 0th term : 0, 1st term : 1
#include

int fibo(int num);
int main() {

    int n = 6;

    int fibonacci = fibo(n);
    printf("fib(%d) : %d", n, fibonacci);

    return 0;
}

// Recursive function to find nth Fibonacci term
int fibo(int n) {

    if (n == 0 || n == 1)  // Base condition
        return n;
    else
        return fibo(n - 1) + fibo(n - 2);
}

Output

fib(6) : 8