Search

Monday, April 1, 2019

C Recursion

In this tutorial, you will learn to create a recursive function in C programming.
Posted By Manisha Gupta
A function that calls itself is known as a 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);
    return 0;
}

int sum(int num)
{
    if (num!=0)
        return num + sum(num-1); // sum() function calls itself
    else
        return num;
}
Output
Enter a positive integer:3
sum = 6

Initially, the sum() is called from the main() function with number passed as an argument.
Suppose, the value of num is 3 initially. During next function call, 2 is passed to the sum()function. This process continues until num is equal to 0.
When num is equal to 0, the if condition fails and the else part is executed returning the sum of integers to the main() function.
Calculation of sum of natural number using recursion

Advantages and Disadvantages of Recursion

Recursion makes program elegant and more readable. However, if performance is vital then, use loops instead as recursion is usually much slower.
Note that, every recursion can be modeled into a loop.
Recursion Vs Iteration? Need performance, use loops, however, code might look ugly and hard to read sometimes. Need more elegant and readable code, use recursion, however, you are sacrificing some performance.  

Follow on Facebook

ManishaTech . 2017 Copyright. All rights reserved. Designed by Blogger Template | Manisha Gupta