Factorial Calculation
Create a C# program to calculate the factorial of a given non-negative integer n. The factorial of a number is the product of all positive integers less than or equal to n.
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Ashutosh Kumar Verma
14-Jun-2024C# Factorial Calculation
When calculating the factor of a number, any positive whole number less than that number must be multiplied by that number. The product of the number n (denoted as n!) is the product of all positive integers less than or equal to n.
Syntax-
5! = 5 * 4 * 3 * 2 * 1 = 120.
3! = 3 * 2 * 1 = 6.
There are two ways mentioned below to calculate the factorial of an integer,
Iterative Approach
Example-
In the above example-
Main method- Asks the user to enter a non-negative integer and verifies the input using int.TryParse and verifies that the number is non-negative. If true, calculate the factor using the CalculateFactorial method.
CalculateFactorial Method- Uses a recursive method with a for loop to calculate a factorial by multiplying the result by any integer from 1 to a given number.
Output-
Recursive Approach
Here is an alternative approach for calculate the factorial of a integer for educational purpose,
Example-
In the above example-
Main method- Same as the general method.
CalculateFactorial Method- Uses recursion to calculate factorial. The base case occurs when the number is 1 or less, in which case it returns 1. Otherwise, it calls itself with the number - 1 and multiplies the result by the number.
Output-
Either approach is correct, but recursive methods are generally more efficient in terms of memory usage because recursive procedures can generate excess stack for very small values of the quantity.
Also, Read: Palindrome Checker