21 Nov C Recursion
When a function calls itself, it is called Recursion in C Language. In another sense, with Recursion, a defined function can call itself. Recursion is a programming approach, that makes code efficient and reduces LOC. It allows certain problems to be solved by breaking down into smaller, similar subproblems.
Recursion can simplify code for problems with natural recursive structure, like factorial calculation, Fibonacci sequence, tree traversal, etc.
The following figure demonstrates how recursion works when we calculate Factorial in C with Recursion:
Recursion Example in C Language
Let us now see how to find the factorial of a number in C language with Recursion.
Here, the main() function calls factFunc(7) to compute the factorial of 7. The result of the function call is stored in the variable res, which is then printed.
If n is 1 or greater, the function returns n multiplied by the result of factFunc(n – 1), effectively breaking down the problem into smaller subproblems:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> // Function prototype int factFun(int n); int main() { int res = factFunc(7); printf("Factorial = %d", res); return 0; } // Function defintion int factFunc(int n) { if (n >= 1) { return n*factFunc(n-1); // Recursive Calls } else { return 1; // Factorial 0 is 1 } } |
Output
1 2 3 |
Factorial = 5040 |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others:
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments