Recursion Function In C

What is Recursion?

Recursion is a special way of nesting functions, where a function calls itself inside it. We must have certain conditions in the function to break out of the recursion, otherwise recursion will occur infinite times.

function1()
{   
    // function1 body
    function1();
    // function1 body
}

 

Example: Factorial of a number using Recursion

#include<stdio.h>

int factorial(int x);       //declaring the function

void main()
{
    int a, b;
    
    printf("Enter a number...");
    scanf("%d", &a);
    b = factorial(a);       //calling the function named factorial
    printf("%d", b);
}

int factorial(int x) //defining the function
{
    int r = 1;
    if(x == 1) 
        return 1;
    else 
        r = x*factorial(x-1);       //recursion, since the function calls itself
    
    return r;
}

Program to print 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.

static keyword is used to initialize the variables only once.

Below is a program to print the fibonacci series using recursion.

#include<stdio.h>
// declaring the function
void printFibo(int );

int main()
{
    printf("\n\n\t\tLetUsLearn - 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 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");
    }
}