How to #Calculate #Factorial of an #Integer #Number in #c sharp and #c plus plus Using #Recursive and #Iterative #Methods.
c++ #code:
#include <iostream> //for cout
#include <conio.h> //for _getch
int factorial(int n) {
int fact = 1;
//for (int i = 1; i <= n; ++i)
//{
// //fact *= i;
// fact = fact*i;
//}
if (n == 0)
return 1;//
else
fact = n * factorial(n - 1);//using recursion
return fact;
}
int main() {
int n, fact = 1;
std::cout << "Enter an integer: " << std::endl;
std::cin >> n;
if (n < 0)
std::cout << "Error! Factorial of a negative number doesn't exist." << std::endl;
else {
fact = factorial(n);
std::cout << "Factorial of " << n << " = " << fact << std::endl;
}
_getch();
//system("pause");
return 0;
}
c# code:
using System;
namespace lec2csharp
{
class Program
{
static int factorial(int n)
{
int fact = 1;
//for (int i = 1; i <= n; ++i)
//{
// fact = fact * i;//fact *= i;
//}
if (n == 0)
return 1;//
else
fact = n * factorial(n - 1);//using recursion
return fact;
}
static void Main()
{
int n,fact = 1;
Console.WriteLine("Enter an integer: ");
n = int.Parse(Console.ReadLine());
if (n < 0)
Console.WriteLine("Error! Factorial of a negative number doesn't exist.");
else
{
fact = factorial(n);
Console.WriteLine("Factorial of {0} = {1}", n, fact);
}
Console.ReadLine();
}
}
}
#csharp #cplusplus #tutorial