//Source Code using Recursion
using System;
public class Recursion_Factorial
{
static long Factorial(int num)
{
if (num <= 1)
return 1;
return num * Factorial(num - 1);
}
public static void Main()
{
int num;
long fact=1;
Console.WriteLine("Enter a Number");
num=Convert.ToInt32(Console.ReadLine());
fact = Factorial(num);
Console.WriteLine("Number = {0} and Factorial = {1}",num,fact);
Console.WriteLine("\nPress any key to exit...");
Console.ReadLine();
}
}
6
Number = 6 and Factorial = 720
Press any key to exit...
-------------------------------------------------------------------------------------
//Using Iteration Method
using System;
public class Program_Factorial_Iteration
{
public static void Main()
{
int num;
long ans;
Console.WriteLine("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());
ans = factorial(num);
Console.WriteLine("Factorial of " + num + " = " + ans);
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadLine();
}
static long factorial(int n)
{
long fact;
if (n <= 1)
return 1;
else
{
fact = 1;
for (int i = n; i > 0; i--)
{
fact = fact * i;
}
return fact;
}
}
}
using System;
public class Recursion_Factorial
{
static long Factorial(int num)
{
if (num <= 1)
return 1;
return num * Factorial(num - 1);
}
public static void Main()
{
int num;
long fact=1;
Console.WriteLine("Enter a Number");
num=Convert.ToInt32(Console.ReadLine());
fact = Factorial(num);
Console.WriteLine("Number = {0} and Factorial = {1}",num,fact);
Console.WriteLine("\nPress any key to exit...");
Console.ReadLine();
}
}
OUTPUT:
Enter a Number6
Number = 6 and Factorial = 720
Press any key to exit...
-------------------------------------------------------------------------------------
//Using Iteration Method
using System;
public class Program_Factorial_Iteration
{
public static void Main()
{
int num;
long ans;
Console.WriteLine("Enter any number: ");
num = Convert.ToInt32(Console.ReadLine());
ans = factorial(num);
Console.WriteLine("Factorial of " + num + " = " + ans);
Console.WriteLine("\n\nPress any key to exit...");
Console.ReadLine();
}
static long factorial(int n)
{
long fact;
if (n <= 1)
return 1;
else
{
fact = 1;
for (int i = n; i > 0; i--)
{
fact = fact * i;
}
return fact;
}
}
}
OUTPUT:
Enter any number:
5
Factorial of 5 = 120
Press any key to exit...
No comments:
Post a Comment