C Program to print Fibonacci Sequence using recursion

What is the Fibonacci sequence?

In the Fibonacci series, each number is the sum of the two previous numbers. The first two numbers in the Fibonacci series are 0 and 1.

The sequence Fn of Fibonacci numbers is defined by the recurrence relation:

Fn = Fn-1 + Fn-2  ( where, n > 1)
with seed values
F0 = 0 and F1 = 1

The beginning of the sequence is thus:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……..

 

See the C program to generate the Fibonacci Sequence using recursion based on the number of terms entered by the user.

#include<stdio.h>


int fibonacciSeries(int num)
{
    //base condition
    if(num == 0 || num == 1)
    {
        return num;
    }
    else
    {
        // recursive call
        return fibonacciSeries(num-1) + fibonacciSeries(num-2);
    }
}

int main()
{
    int num, i;

    printf("Enter no. of terms: ");
    scanf("%d", &num);

    if(num < 0)
    {
        printf("Enter +ve number");
        exit(1);
    }

    printf("Fibonacci series\n");

    for (i = 0 ; i<num ; i++ )
    {
        printf("%d\t", fibonacciSeries(i));
    }

    return 0;
}

Output:

Enter no. of terms: 5
0 1 1 2 3

Leave a Reply

Your email address will not be published. Required fields are marked *