How to implement recursion in C++?
Hi everyone! I'm new to C++ and trying to understand recursion. I wrote a simple function to calculate factorial, but it works incorrectly. Here's the code:\n\n```cpp\n#include \nusing namespace std;\n\nint factorial(int n) {\n if (n == 0) {\n return 1;\n } else {\n return n * factorial(n - 1);\n }\n}\n\nint main() {\n int num = 5;\n cout << "Factorial " << num << " = " << factorial(num) << endl;\n return 0;\n}\n```\n\nI expect to get 120 for the number 5, but sometimes the program crashes or returns strange values. I tried adding a check for negative numbers, but it didn't help. I also read about stack overflow, but I'm not sure how to avoid it. Maybe the problem is that I'm not using the base case correctly? Or do I need to do something with the type?
No answers yet.
Log in to leave an answer