using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Factorial
{
class Program
{
//
Using Recursion
public static long GetFactorialUsingRecursion(int num)
{
if (num
== 0)
{
return 1;
}
return num
* GetFactorialUsingRecursion(num - 1);
}
//
Using For Loop
public static long GetFactorialUsingForLoop(int num)
{
long fact
= 1;
for (int i
= 1; i <= num; i++)
{
fact
= fact * i;
}
return fact;
}
//
Using While Loop
public static long GetFactorialUsingWhileLoop1(int num)
{
int count
= 1;
long fact
= 1;
while (count
<= num)
{
fact
= fact * count;
count++;
}
return fact;
}
//
Using While Loop
public static long GetFactorialUsingWhileLoop2(int num)
{
long fact
= 1;
while (num
> 1)
{
fact
= num * fact;
num
= num - 1;
}
return fact;
}
static void Main(string[]
args)
{
int num
= 5;
Console.WriteLine("Using
Recursion - {0} factorial is {1}", num, GetFactorialUsingRecursion(num));
Console.WriteLine("Using
For Loop - {0} factorial is {1}", num, GetFactorialUsingForLoop(num));
Console.WriteLine("Using
While Loop 1 - {0} factorial is {1}", num, GetFactorialUsingWhileLoop1(num));
Console.WriteLine("Using
While Loop 2 - {0} factorial is {1}", num, GetFactorialUsingWhileLoop2(num));
Console.ReadLine();
}
}
}
Output:
No comments:
Post a Comment