Recursion In C

Introduction

The C programming language includes a number of features that assist programmers in making their code more efficient and simple. Recursion is one of the most complicated and useful concepts in C.

When a function calls a copy of itself in C, the process is referred to as recursion. To put it simply, when a function calls itself, this is referred to as recursion. The function is also referred to as a recursive function.

Tasks such as sorting, searching, and traversal problems, can benefit from recursion. When using recursion, you must define an exit condition on that function; otherwise, it will enter an infinite loop.

Syntax of a recursive function is as follows:

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

int main()
{
    ... .. ...
    recurse();
    ... .. ...
}
Process of Recursion

The recursion will continue until a condition is met to stop it.

To avoid infinite recursion, we can use an if…else statement (or a similar approach) where one branch makes the recursive call and the other does not.

Recursion Example ➟ Sum of Natural Numbers

# include <stdio.h>
# include <conio.h>

// www.raviroza.com

// function prototype/declaration
int sum(int n);

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

// main function
void main() 
{
    int n, s;

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

    s = sum(n);

    printf ("sum = %d", s);   
    getch(); 
}

Output

Enter a positive number : 4
sum = 10

Conclusion

Recursion makes the program more elegant. However, if performance is critical, use loops instead of recursion, as recursion is typically much slower.

Having said that, recursion is a crucial concept. It’s commonly used in data structures and algorithms. Recursion, for example, is commonly used in problems such as tree traversal.

Image Source : https://www.programiz.com/c-programming/c-recursion