Recursion in C programming

In this tutorial, we will get insight on what is recursion in C programming and how execution of recursive function takes place.

Syntax of recursion

void recursiveFunction()
{
    ... .. ...
    recursiveFunction();
    ... .. ...
}

int main()
{
    ... .. ...
    recursiveFunction();
    ... .. ...
}

In above example, recursiveFunction calls itself.

recursive function in C
fig : how recursive function works

Recursion leads to infinite loop if it is not terminated. So there must be condition to end recursion in program.

Example to calculate factorial of entered number using recursive function

#include <stdio.h>
 
int factorial(int);
 
int main()
{
    int num;
    int result;
 
    printf("Enter a number : ");
    scanf("%d", &num);
    if (num < 0)
    {
        printf("Factorial of negative number not possible\n");
    }
    else
    {
        result = factorial(num);
        printf("The Factorial of %d is %d.\n", num, result);
    }
    return 0;
}
int factorial(int n)
{
    if (n<= 1)
    {
        return 1;
    }
    else
    {
        return(n* factorial(n- 1));
    }
}

Output

Enter a number : 3
The Factorial of 3 is 6.

In above example, the recursion occurs until  value of n <= 1  inside factorial  function. It works in following way: