What is a recursion

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();
    ... .. ...
}

Example: Sum of Natural Numbers Using Recursion

  1. #include <stdio.h>
  2. int sum(int n);
  3. int main() {
  4. int number, result;
  5. printf("Enter a positive integer: ");
  6. scanf("%d", &number);
  7. result = sum(number);
  8. printf("sum = %d", result);
  9. return 0;
  10. }
  11. int sum(int n) {
  12. if (n != 0)
  13. // sum() function calls itself
  14. return n + sum(n-1);
  15. else
  16. return n;
  17. }
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 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.
Calculation of sum of natural number using recursion






Post a Comment

0 Comments