C (programming language)
C program to print factorial of given number using function
Understanding Factorials
- Definition: The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n.
- Representation: Mathematically, n! = n * (n-1) * (n-2) * … * 2 * 1.
- Examples:
- 5! = 5 * 4 * 3 * 2 * 1 = 120
- 0! = 1 (by definition)
Key Concepts for Implementation
- Functions: C programs use functions to organize code and make it reusable.
- Iterative Approach: Factorials can be calculated using a loop that iterates from 1 to n, multiplying the numbers together.
- Recursive Approach: Factorials can also be calculated recursively, where a function calls itself with a smaller value of n until a base case is reached.
Implementation Using a Function (Iterative Approach)
Code:
C
#include <stdio.h>
long long factorial(int n) {
long long result = 1; // Initialize result to 1
for (int i = 1; i <= n; i++) {
result *= i; // Multiply result by each number from 1 to n
}
return result; // Return the calculated factorial
}
int main() {
int num;
printf("Enter a non-negative number: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
long long fact = factorial(num);
printf("Factorial of %d = %lld\n", num, fact);
}
return 0;
}
Explanation:
- Header:
#include <stdio.h>
includes the standard input/output library for functions likeprintf
andscanf
. - Function
factorial
:- Takes an integer
n
as input. - Initializes
result
to 1. - Uses a
for
loop to iterate from 1 ton
. - In each iteration, multiplies
result
byi
. - Returns the calculated
result
.
- Takes an integer
- Main Function:
- Prompts the user to enter a number.
- Checks if the number is non-negative.
- Calls the
factorial
function to calculate the factorial. - Prints the result.
Implementation Using a Function (Recursive Approach)
Code:
C
#include <stdio.h>
long long factorial(int n) {
if (n == 0) {
return 1; // Base case: factorial of 0 is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}
// Rest of the main function remains the same
Explanation:
- The recursive approach breaks down the problem into smaller, self-similar subproblems.
- The base case stops the recursion when
n
reaches 0. - The recursive case calls
factorial(n - 1)
to calculate the factorial of a smaller number.
Additional Considerations
- Data Type: Choose an appropriate data type (like
long long
) to accommodate larger factorial values. - Error Handling: Consider handling invalid input (e.g., negative numbers) gracefully.
- Optimization: Explore iterative and recursive approaches for efficiency based on specific use cases.