Write a program to calculate the factorial value of the input number n! Use the incrementation formula ( i++ ) for your solution instead of decrementation formula (i-‐-‐).
Apply the three looping statements for your solutions:
Enter a no. 4 Factorial value is: 24 (The computation is: 1*2*3*4=24)
1st Solution – using for loop
2nd Solution – using while loop
3rd Solution-‐ using do while loop
using System;
using System.Collections.Generic;
namespace App
{
class Program
{
public static void Main()
{
Console.Write("Enter a no.: ");
int n = int.Parse(Console.ReadLine());
Console.WriteLine("Factorial value is (using - for loop): {0}", ComputeFactorialWithFor(n));
Console.WriteLine("Factorial value is (using - while loop): {0}", ComputeFactorialWithWhile(n));
Console.WriteLine("Factorial value is (using - do while loop): {0}", ComputeFactorialWithDoWhile(n));
Console.ReadLine();
}
private static int ComputeFactorialWithDoWhile(int n)
{
int factorial = 1;
int i = 1;
do
{
factorial *= i;
} while (++i <= n);
return factorial;
}
private static int ComputeFactorialWithWhile(int n)
{
int factorial = 1;
int i = 1;
while (++i <= n)
{
factorial *= i;
}
return factorial;
}
private static int ComputeFactorialWithFor(int n)
{
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
return factorial;
}
}
}
Comments
Leave a comment