Fibonacci Series Using Recursion

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to create a C program to print the Fibonacci series using recursion. A Fibonacci series is defined as a series in which each number is the sum of the previous two numbers with 1, 1 being the first two elements of the series.

Create a new C file

Create a new C file named main.c in the ~/project/ directory.

Include necessary libraries

Include the necessary standard input/output library stdio.h.

#include<stdio.h>

Define printFibo function

Define a function named printFibo with a parameter aj. It is used to print the Fibonacci series.

void printFibo(int aj)
{
    static long int first = 0, second = 1, sum;
    if(aj > 1)
    {
        sum = first + second;
        first = second;
        second = sum;
        printf("%ld ", sum);
        printFibo(aj-1);    // recursive call
    }
    else
    {
        // after the elements, for line break
        printf("\n\n\n");
    }
}

Define main function

Define the main function. Take the input from the user for the total number of elements in the Fibonacci series, and pass it to the printFibo function.

int main()
{
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
    int k, n;
    long int i = 0, j = 1;
    printf("Enter the length of the Fibonacci series: ");
    scanf("%d", &n);
    printf("\n\nFirst %d terms of the Fibonacci series are:\n\n\n",n);
    printf("%d ", 1);
    printFibo(n);
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

Finalize the code

Now, the complete program to print the Fibonacci series using recursion is given below:

#include<stdio.h>

// declaring the function
void printFibo(int);

int main()
{
    printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
    int k, n;
    long int i = 0, j = 1;
    printf("Enter the length of the Fibonacci series: ");
    scanf("%d", &n);
    printf("\n\nFirst %d terms of the Fibonacci series are:\n\n\n",n);
    printf("%d ", 1);
    printFibo(n);
    printf("\n\n\t\t\tCoding is Fun !\n\n\n");
    return 0;
}

void printFibo(int aj)
{
    static long int first = 0, second = 1, sum;
    if(aj > 1)
    {
        sum = first + second;
        first = second;
        second = sum;
        printf("%ld ", sum);
        printFibo(aj-1);    // recursive call
    }
    else
    {
        // after the elements, for line break
        printf("\n\n\n");
    }
}

Summary

In this lab, you have learned how to create a C program to print the Fibonacci series using recursion. You now understand the process of defining functions and utilizing recursion to iterate through the necessary series.

Other C Tutorials you may like