Calculate the factorial of a given number
Here is C# program to calculate the factorial of a given number without using recursion:
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
long factorial = CalculateFactorial(number);
Console.WriteLine($"Factorial of {number} is: {factorial}");
}
static long CalculateFactorial(int number)
{
long factorial = 1;
for (int i = 2; i <= number; i++)
{
factorial *= i;
}
return factorial;
}
}
In this program, the 'CalculateFactorial' method takes an integer 'number' as input and calculates the 'factorial' of that 'number' using a loop. It initializes the 'factorial' variable to 1 and then iterates from 2 to number. In each iteration, it multiplies factorial by the current iteration value. Finally, it returns the calculated factorial.
The 'Main' method prompts the user to enter a number, calls the 'CalculateFactorial' method with the user input, and displays the result.
Note that the program uses the 'long' data type to store the factorial value, as the factorial of large numbers can quickly exceed the range of the 'int' data type.