21 Jan C++ Recursion
In C++, when a function calls itself, it is called Recursion. In another sense, with Recursion, a defined function can call itself. Recursion is a programming approach, which makes code efficient and reduces LOC.
The following figure demonstrates how recursion works when we calculate Factorial in C++ with Recursion:
Recursion Example in C++
Let us now see how to find the factorial of a number in C++ with Recursion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> using namespace std; int factFunc(int n) { if (n >= 1) { return n*factFunc(n-1); // Recursive Calls } else { return 1; // Factorial 0 is 1 } } int main() { int res = factFunc(7); cout<<"Factorial = "<<res; return 0; } |
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
No Comments