C# Program - Find Factorial of a Number
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 × 4 × 3 × 2 × 1 = 120
4! = 4 × 3 × 2 × 1 = 24
Method 1: Using Recursive method
In the example below, a recursive method called factorial() is used to calculate factorial of a number.
using System; 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)); } }
The above code will give the following output:
10! = 3628800 6! = 720
Method 2: Using Iterative method
The factorial of a number can also be calculated using iterative method.
using System; 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)); } }
The above code will give the following output:
10! = 3628800 6! = 720
Method 3: Using Ternary Operator
In the example below, the factorial of a number is calculated using ternary operator.
using System; 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)); } }
The above code will give the following output:
10! = 3628800 6! = 720
Recommended Pages
- C# Program - To Check Prime Number
- C# Program - Bubble Sort
- C# Program - Selection Sort
- C# Program - Maximum Subarray Sum
- C# Program - Reverse digits of a given Integer
- C# Program - Merge Sort
- C# Program - Shell Sort
- Stack in C#
- Queue in C#
- C# Program - Find LCM of Two Numbers
- C# Program - To Check Whether a Number is Palindrome or Not
- C# Program - To Check Whether a String is Palindrome or Not
- C# Program - Heap Sort
- C# Program - Quick Sort
- C# - Swap Two Numbers without using Temporary Variable
- C# Program - To Check Armstrong Number
- C# Program - Counting Sort
- C# Program - Radix Sort
- C# Program - Find Largest Number among Three Numbers
- C# Program - Print Floyd's Triangle