Factorial using Recursion

Calculate Factorial using Recursion in C++

BeginnerTopic: Recursion Programs
Back

C++ Factorial using Recursion Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

// Recursive function to calculate factorial
int factorial(int n) {
    // Base case
    if (n == 0 || n == 1) {
        return 1;
    }
    
    // Recursive case
    return n * factorial(n - 1);
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    
    if (num < 0) {
        cout << "Factorial is not defined for negative numbers." << endl;
    } else {
        int result = factorial(num);
        cout << "Factorial of " << num << " = " << result << endl;
    }
    
    // Display factorial of first 10 numbers
    cout << "\nFactorials of 0-10:" << endl;
    for (int i = 0; i <= 10; i++) {
        cout << i << "! = " << factorial(i) << endl;
    }
    
    return 0;
}
Output
Enter a number: 5
Factorial of 5 = 120

Factorials of 0-10:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

Understanding Factorial using Recursion

Recursion is when a function calls itself. Factorial: n! = n * (n-1)!. Base case: 0! = 1! = 1. Recursive case: n! = n * (n-1)!. Each recursive call reduces problem size. Stack frames are created for each call. Ensure base case is reachable to avoid infinite recursion.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents