Factorial of a number is obtained from the result of multiplying a series of descending natural numbers.
This C# Program generates Factorial of the Number obtained from the user.
1. Using For Loop:
/*
* C# Program to Generate the Factorial of Given Number
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace factorial
{
class Program
{
static void Main(string[] args)
{
int i, number, fact;
Console.WriteLine("Enter the Number");
number = int.Parse(Console.ReadLine());
fact = number;
for (i = number - 1; i >= 1; i--)
{
fact = fact * i;
}
Console.WriteLine("\nFactorial of Given Number is: "+fact);
Console.ReadLine();
}
}
}
Here is the output of the C# Program:
Enter the Number 5 Factorial of Given Number is: 120
You can calculate factorial using recursion and while loop also.
2. Using Recursion:
public double factorial_Recursion(int number)
{
if (number == 1)
return 1;
else
return number * factorial_recursion(number - 1);
}
3. Using While loop:
public double factorial_WhileLoop(int number)
{
double result = 1;
while (number != 1)
{
result = result * number;
number = number - 1;
}
return result;
}
Source: csharpstar
The Tech Platform
Comments