C Programming Recursion

In this tutorial, you will learn to create a recursive function in C programming.
Recursion in C programming

A function that calls itself is known as recursive function. And, this technique is known as recursion.


How recursion works?

void recurse()
{
    ... .. ...
    recurse();
    ... .. ...
}

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

How recursion works in C programming?

The recursion continues until some condition is met to prevent it. To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call and other doesn't.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main()
{
    int number, result;

    printf("Enter a positive integer: ");
    scanf("%d", &number);

    result = sum(number);

    printf("sum=%d", result);
}

int sum(int n)
{
    if (n!=0)
        return n + sum(n-1); // sum() function calls itself
    else
        return n;
}

Output

Enter a positive integer:
3
6

Initially, the sum() is called from the main() function with number passed as an argument.

Suppose, the value of n is 3 initially. During next function call, 2 is passed to the sum() function. In next function call, 1 is passed to the function. This process continues until n is equal to 0.

When n is equal to 0, there is no recursive call and the sum of integers is returned to the main() function.

Calculation of sum of natural number using recursion


Advantages and Disadvantages of Recursion

Recursion makes program elegant and cleaner. All algorithms can be defined recursively which makes it easier to visualize and prove. 

If the speed of the program is vital then, you should avoid using recursion. Recursions use more memory and are generally slow.