🧮 Factorial of a Number Using Recursion in C++

Factorial Using Recursion in C++

🧮 Factorial of a Number Using Recursion in C++

Calculating the factorial of a number using recursion is a classic example in programming. It not only demonstrates the power of recursive functions but also helps in building problem-solving and algorithmic thinking.

📘 What is Recursion?

Recursion is a programming technique where a function calls itself to solve smaller subproblems of the original task. It is particularly useful for tasks that can be divided into similar subtasks.

💡 What is Factorial?

The factorial of a non-negative integer n (written as n!) is the product of all positive integers less than or equal to n.

Example:  
5! = 5 × 4 × 3 × 2 × 1 = 120  
0! = 1 (by definition)
  

📄 C++ Code: Factorial Using Recursion


#include <iostream>
using namespace std;

// Recursive function to calculate factorial
unsigned long long factorial(int n) {
    if (n == 0)
        return 1;
    else
        return n * factorial(n - 1);
}

int main() {
    int number;

    // Input from user
    cout << "Enter a non-negative integer: ";
    cin >> number;

    if (number < 0) {
        cout << "Factorial is not defined for negative numbers." << endl;
    } else {
        // Call recursive function
        cout << "Factorial of " << number << " = " << factorial(number) << endl;
    }

    return 0;
}
    

✅ Sample Output

Enter a non-negative integer: 6  
Factorial of 6 = 720
  

📝 How It Works

  • Base Case: If n == 0, return 1 (since 0! = 1).
  • Recursive Case: n * factorial(n - 1) continues until n reaches 0.
  • Each recursive call multiplies n with the factorial of the next smaller number.

📘 Definition: Factorial Using Recursion

Factorial using recursion in C++ is a method where a function repeatedly calls itself with decremented values until it reaches the base case (usually 0). This approach mimics the mathematical definition of factorials and is widely used for educational and algorithmic purposes.

Recursive solutions are elegant and compact but may consume more memory for deep calls. Understanding recursion is crucial for mastering advanced programming concepts like divide-and-conquer and backtracking.

🎯 Final Thoughts

Learning how to implement recursion helps in mastering problems that require self-similar solutions. Factorial using recursion is a perfect starting point and a frequent topic in coding interviews and academic exams.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences