Recursive Function to Calculate Factorial of a Number in C++

In this exercise, you will implement a recursive function in C++ that calculates the factorial of a given number. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and defined as:

n! = n × (n-1) × (n-2) × ... × 1

Recursion is a programming technique where a function calls itself to solve a smaller instance of the same problem. Factorials are a classic use case for practicing recursion and help reinforce your understanding of function calls, base cases, and recursion trees.

You will write a function that calls itself with decreasing values of n until it reaches the base case (factorial of 0 is 1), then returns the result up the recursive chain.

Group

Functions in C++

Objective

1. Create a function named factorial that takes an integer as input.
2. Use an if statement to define the base case: if the number is 0, return 1.
3. For the recursive case, return n multiplied by the factorial of n - 1.
4. In the main function, prompt the user to enter a number.
5. Call the recursive function and display the result.

Implement a recursive function to calculate the factorial of a number.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Recursive function to calculate the factorial of a number
int factorial(int n) {
    if (n == 0) {
        return 1; // Base case: factorial of 0 is 1
    }
    return n * factorial(n - 1); // Recursive call
}

// Main function
int main() {
    int number;

    // Ask the user to enter a number
    cout << "Enter a non-negative integer: ";
    cin >> number;

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

    return 0; // End of the program
}

 Output

Enter a non-negative integer: 5
Factorial of 5 is: 120

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.