5 Factorial = 5! = 5*4*3*2*1 = 120
4 Factorial = 4! = 4*3*2*1 = 24
3 Factorial = 3! = 3*2*1 = 6
Zero এর Factorial কিন্তু 1।
নিচের program এ দেখানো হল কিভাবে একটি number এর factorial বের করতে হয়
using System;
namespace MainPrograms
{
class Program
{
static void Main(string[] args)
{
// Prompt the user to enter their target number to calculate factorial
Console.WriteLine("please enter the number
for which you want to calculate the factorial");
try
{
// Read the input from console and convert to integer data type
int iTarget = Convert.ToInt32(Console.ReadLine());
// Factorial of Zero is 1
if (iTarget==0)
{
Console.WriteLine("Factorial of Zero =1");
}
// Compute factorial only for non negative numbers
else if (iTarget<0)
{
Console.WriteLine("please enter a positive number");
}
// If the number is non zero and non negative
else
{
// Declare a variable to hold the factorial result.
double dFactorialResult = 1;
// Use for loop to calcualte factorial of the target number
for (int i = iTarget; i >=1; i--)
{
dFactorialResult = dFactorialResult * i;
}
// Output the result to the console
Console.WriteLine("Factorial of {0}={1}", iTarget, dFactorialResult);
}
}
catch (FormatException)
{
// We get format exception if user enters a word instead of number
Console.WriteLine("please enter a valid number");
}
catch (OverflowException)
{
// We get overflow exception if user enters a very big number,
// which a variable of type Int32 cannot hold
Console.WriteLine("Please enter a number between 1 and {0}",
Int32.MaxValue);
}
catch (Exception)
{
// Any other unforeseen error
Console.WriteLine("There is a problem! Please try later");
}
finally
{
Console.ReadKey();
}
}
}
}
No comments:
Post a Comment