Ticker

6/recent/ticker-posts

Recursion in C Programming

 Recursion in C Programming



A recursive function is one that calls itself, and such function calls are referred to as recursive calls. There are various recursive calls in recursion. It is, nonetheless, critical to impose a recursion termination condition. Although recursion code is shorter than iterative code, it is more harder to comprehend.

Recursion is a feature of the C programming language, which allows a function to call itself. However, when employing recursion, programmers must ensure that the function has an exit condition, or else it would enter an indefinite loop.

Example: Sum of Natural Numbers using Recursion

int sum(int n);

int main() {
    int num, result;

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

    result = sum(num);

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

int sum(int n) {
    if (n != 0)
        return n + sum(n-1); 
    else
        return n;
}
Output : 

Enter a positive number : 5
Sum = 15

The Benefits and Drawbacks of Recursion

The use of recursion in a program makes it more elegant. If performance is critical, however, loops should be used instead of recursion, which is normally much slower.

Recursion, on the other hand, is a crucial idea. It's very common in data structures and algorithms. Recursion is commonly used in situations like tree traversal.

Post a Comment

0 Comments