The factorial of a non-negative integer is the product of all positive integers less than or equal to . The factorial of is denoted as .
For example:
- (by definition)
Logic to Calculate Factorial:
- If is 0, return 1 (base case).
- For , multiply by the factorial of .
- This can be done using either a recursive or iterative approach.
Program:
Here’s a simple C program to calculate the factorial of a number using both iterative and recursive methods.
Iterative Approach:
Recursive Approach:
Explanation:
Variables:
int n
: Holds the non-negative integer input by the user.unsigned long long factorial
: Stores the computed factorial value. Usingunsigned long long
allows handling larger results.
Input:
- The user is prompted to enter a non-negative integer.
Negative Input Check:
- The program checks if is negative and informs the user that factorials for negative numbers are not defined.
Iterative Approach:
- A
for
loop runs from 1 to , multiplying thefactorial
variable by each integer .
- A
Recursive Approach:
- The
factorial
function calls itself, reducing by 1 each time until it reaches the base case of 0.
- The
Output:
- The program prints the calculated factorial.
Sample Output:
Example 1 (Iterative):
Example 2 (Recursive):
Key Points:
- Base Case: In the recursive approach, the base case (0! = 1) is crucial to prevent infinite recursion.
- Data Type:
unsigned long long
is used to accommodate larger factorial values, especially for numbers greater than 20, where the factorial exceeds the limits of standard data types. - Factorial Growth: Factorials grow very quickly, which is an important consideration in both iterative and recursive implementations.