C++ Online Compiler
Example: Recursive Factorial in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Recursive Factorial #include <iostream> // Function to calculate factorial recursively int factorial(int n) { // Base case: If n is 0 or 1, factorial is 1. if (n == 0 || n == 1) { return 1; } // Recursive step: n * factorial(n-1) else { return n * factorial(n - 1); } } int main() { // Step 1: Call the factorial function with an example number int num = 5; long long result = factorial(num); // Using long long for potentially large results // Step 2: Print the result std::cout << "The factorial of " << num << " is: " << result << std::endl; // Step 3: Test with another number num = 0; result = factorial(num); std::cout << "The factorial of " << num << " is: " << result << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS