Calculating Factorials in C#: A Simple and Efficient Iterative Approach
Learn how to calculate factorials in C# using an iterative approach. This tutorial provides a clear code example, explains the factorial calculation process, and demonstrates error handling for invalid inputs, providing a practical and efficient solution.
Calculating Factorials in C#
Understanding Factorials
The factorial of a non-negative integer n (denoted as n!) is the product of all positive integers less than or equal to n. For example, 5! (5 factorial) is 5 * 4 * 3 * 2 * 1 = 120. Factorials are commonly used in mathematics, particularly in combinatorics (calculations involving combinations and permutations).
C# Factorial Program using a `for` loop
This C# program calculates the factorial of a number entered by the user using a `for` loop. It iteratively multiplies numbers from 1 up to the input number to compute the factorial. Error handling (e.g., checking for negative input) is not included in this simple example.
C# Code
using System;
public class FactorialExample {
public static void Main(string[] args) {
Console.Write("Enter a non-negative integer: ");
int number = int.Parse(Console.ReadLine());
long factorial = CalculateFactorial(number);
Console.WriteLine($"Factorial of {number}: {factorial}");
}
public static long CalculateFactorial(int n) {
if (n < 0) {
throw new ArgumentException("Input must be non-negative.");
}
long factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
return factorial;
}
}
Conclusion
This program demonstrates a straightforward method for calculating factorials in C#. The `for` loop efficiently computes the factorial, and the `CalculateFactorial` function handles potential errors due to negative inputs, making the program more robust.