OverIQ.com

C Program to print Fibonacci Sequence using recursion

Last updated on September 24, 2020


The following is a C Program to print Fibonacci Sequence using recursion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/****************************************************
 Program to print Fibonacci Sequence using recursion 
 * 
 * Enter terms: 10
 * 0 1 1 2 3 5 8 13 21 34 
 ****************************************************/

#include<stdio.h> // include stdio.h library
int fibonacci(int);

int main(void)
{    
    int terms;

    printf("Enter terms: ");
    scanf("%d", &terms);       

    for(int n = 0; n < terms; n++)
    {
        printf("%d ", fibonacci(n));
    }

    return 0; // return 0 to operating system
}

int fibonacci(int num)
{    

    //base condition
    if(num == 0 || num == 1)
    {
        return num;
    }

    else
    {
        // recursive call
        return fibonacci(num-1) + fibonacci(num-2);
    }

}

Try it now

Expected Output:

1
2
Enter terms: 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

How it works #

The following figure shows how the evaluation of fibonacci(3) takes place:


Recommended Reading: