Solution 12 to 25
Solution 19

Calculating Factorial Using Recursion

This program demonstrates how to calculate the factorial of a number using recursion. Factorials are a fundamental concept in mathematics, often used in combinatorics and algebra. The factorial of a non-negative integer ( n ) is the product of all positive integers less than or equal to ( n ). For example, the factorial of 5 (denoted as 5!) is ( 5 \times 4 \times 3 \times 2 \times 1 = 120 ). In this program, the factorial function is implemented recursively, meaning that the function calls itself to perform the calculation. This approach is elegant and concise, but it is important to handle base cases correctly to avoid infinite recursion.

Code Breakdown

Algorithm

  1. Start
  2. Input: Read the integer x from the user.
  3. Call the Recursive Function: Call the function factorial(x) to calculate the factorial of x.
    • Function factorial(n):
      1. Base Case: If n is 0, return 1. This is because (0! = 1) by definition.
      2. Recursive Case: If n is greater than 0, return n multiplied by the result of factorial(n-1). This breaks down the problem into smaller instances.
  4. Output: Print the result of the factorial calculation.
  5. End

Code Explanation

Example Flowchart

+----------------------------------+
|           Start                  |
+----------------------------------+
                |
                v
+----------------------------------+
|   Input number 'n'               |
+----------------------------------+
                |
                v
+----------------------------------+
| Is 'n' equal to 0?               |
+----------------------------------+
      |             |
      | Yes         | No
      v             |
+----------------------------------+
| Return 1 (Factorial of 0)        |
+----------------------------------+
                |
                v
+----------------------------------+
| Calculate 'n * factorial(n-1)'   |
+----------------------------------+
                |
                v
+----------------------------------+
| Return the result                |
+----------------------------------+
                |
                v
+----------------------------------+
|           End                    |
+----------------------------------+