Here's a C# program that calculates and prints the factorial of a given number:
csharp
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int number))
{
long factorial = Factorial(number);
Console.WriteLine($"The factorial of {number} is {factorial}.");
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
static long Factorial(int n)
{
if (n <= 1)
{
return 1;
}
return n * Factorial(n - 1);
}
}
Explanation:
Main Method:
Prompts the user to enter a number.
Uses int.TryParse
to safely parse the user input into an integer.
Calls the Factorial
method to calculate the factorial of the entered number.
Prints the result.
Factorial Method:
Uses recursion to calculate the factorial.
If n
is less than or equal to 1, it returns 1 (base case).
Otherwise, it returns n
multiplied by the factorial of n-1
.
Iterative Approach:
For larger numbers or to avoid the overhead of recursion, you can also implement an iterative approach:
csharp
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
if (int.TryParse(Console.ReadLine(), out int number))
{
long factorial = FactorialIterative(number);
Console.WriteLine($"The factorial of {number} is {factorial}.");
}
else
{
Console.WriteLine("Invalid input. Please enter a valid number.");
}
}
static long FactorialIterative(int n)
{
long result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
return result;
}
}
Explanation of the Iterative Approach:
FactorialIterative Method:
Initializes result
to 1.
Uses a for
loop to multiply result
by each integer from 2 up to n
.
Returns the computed factorial.
Choose the approach that best fits your needs and the constraints of your program. Let me know if you have any specific requirements or further questions!