C Recursion
C Recursion: In this tutorial, you will learn to write recursive functions in C programming with the help of an example.
A function that calls itself is known as a recursive function. What’s more, this method is known as recursion.
How recursion works?
void recurse() { ... .. ... recurse(); ... .. ... } int main() { ... .. ... recurse(); ... .. ... }
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 sum() is called from the main() function with the number passed as an argument.
Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to the sum() function. This process continues until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is executed returning the sum of integers ultimately to the main() function.
Advantages and Disadvantages of Recursion
Recursion makes the program exquisite. In any case, if the execution is crucial, use circles rather as recursion are normally much slower.
That being stated, recursion is a significant idea. It is as often as possible used in data structure and algorithms. For instance, it is entirely expected to utilize recursion in issues, for example, tree traversal.
Please feel free to give your comment if you face any difficulty here.