C++ Online Compiler
Example: Factorial using Recursion in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Factorial using Recursion #include <iostream> using namespace std; // Function to calculate factorial using recursion long long factorial(int n) { // Base case: if n is 0 or 1, factorial is 1 if (n == 0 || n == 1) { return 1; } // Recursive case: n * factorial(n-1) else { return n * factorial(n - 1); } } int main() { // Step 1: Declare a variable to store the input number int number; // Step 2: Prompt the user to enter a non-negative integer cout << "Enter a non-negative integer: "; cin >> number; // Step 3: Check for invalid input (negative number) if (number < 0) { cout << "Factorial is not defined for negative numbers." << endl; } // Step 4: Calculate and display the factorial for valid input else { long long result = factorial(number); cout << "Factorial of " << number << " is: " << result << endl; } return 0; }
Output
Clear
ADVERTISEMENTS