Recursion In C Programming Language

Recursion In C Programming Language

With the aid of an example, you will learn how to create recursion functions in C programming in this article.

Recursive functions are defined as those that call themselves repeatedly. And this method is called a recursive function.

A recursive function is an act of repeating things in a way that is self-similar. A recursive call of the function is what is referred to in programming languages.

when a program enables you to call a function inside another function. void recursive(); recursive(); int main(); recursive(); function calls itself

A recursive function, or a function that calls itself, is supported in the C programming language. The function will enter an infinite loop if recursive function is used,

So programmers must be careful to define an exit condition from the function.

Numerous mathematical problems can be solved using recursive functions, such as determining a number’s factorial or creating Fibonacci sequences.

How does recursion work?

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

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

Up until a condition is met to stop it, the recursion keeps happening.

When one branch performs the recursive call while the other doesn’t, and if…else statement (or a similar approach) can be used to prevent infinite recursion.

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);
    return 0;
}

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

Output

Enter a positive integer:3
sum = 6

Initially, the number is supplied as an argument when calling sum() from the main() function.

Let’s say that n in the sum() function starts out at 3. 2 is provided to the sum() function on the subsequent function call. This method keeps going till n = 0.

If the condition fails when n is equal to 0, the else clause is then run, returning the sum of the numbers to the main() function.

Benefits and Drawbacks of Recursion

Programs are made elegant by recursion. Recursive functions are typically slower, so loops should be used in place of it if performance is crucial.

Recursion is a crucial idea, in light of this. It is extensively utilized in algorithms and data structures. Recursion is frequently used, for instance, to solve issues like tree traversal.

Leave a Reply