C# Program - Find Factorial of a Number


Advertisements

The factorial of a positive integer is the multiplication of all positive integer less than or equal to that number.

$$factorial$$ $$of$$ $$number$$ $$n$$ = $$n! = n(n-1)(n-2)...1$$

For Example:

$$5! = 5\times4\times3\times2\times1 = 120$$

$$4! = 4\times3\times2\times1 = 24$$

Example: Using Recursive method

In the below example, a recursive method called factorial() is used to calculate factorial of a number.

using System;

namespace MyApplication { 
  class MyProgram {
    static int factorial(int x) {
      if (x == 0 || x == 1)
        {return 1;}
      else 
        {return x*factorial(x-1);} 
    }  

    static void Main(string[] args) {
      Console.WriteLine("10! =  " + factorial(10));
      Console.WriteLine("6! =  " + factorial(6));
    }
  }
}

Output

10! =  3628800
6! =  720

Example: Using Iterative method

The factorial of a number can also be calculated using iterative method.

using System;

namespace MyApplication { 
  class MyProgram {
    static int factorial(int x) {
      int finalnum = 1;
      for(int i = x; i > 0; i--)
      {
        finalnum = finalnum * i;
      }
      return finalnum;  
    }  

    static void Main(string[] args) {
      Console.WriteLine("10! =  " + factorial(10));
      Console.WriteLine("6! =  " + factorial(6));
    }
  }
}

Output

10! =  3628800
6! =  720

Example: Using Ternary Operator

In the below example, the factorial of a number is calculated using ternary operator.

using System;

namespace MyApplication { 
  class MyProgram {
    static int factorial(int x) {
      int y = (x == 0 || x == 1)? 1 : x*factorial(x-1);
      return y;  
    }  

    static void Main(string[] args) {
      Console.WriteLine("10! =  " + factorial(10));
      Console.WriteLine("6! =  " + factorial(6));
    }
  }
}

Output

10! =  3628800
6! =  720



Recommended Pages


Advertisements