Example: Sum of Natural Numbers Using Recursion
Example: Sum of Natural Numbers Using Recursion
Recursion
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
result = sum(number);
printf("sum=%d", result);
}
Output
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.
Advantages and Disadvantages of Recursion
Recursion makes program elegant and cleaner. All algorithms can be defined
recursively which makes it easier to visualize and prove.
If the speed of the program is vital then, you should avoid using recursion.
Recursions use more memory and are generally slow. Instead, you can use
loop.