
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Three Different ways to calculate factorial in C#
To calculate a factorial in C#, you can use any of the following three ways −
Calculate factorial with for loop
Example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace factorial { class Test { static void Main(string[] args) { int i, res; int value = 5; res = value; for (i = value - 1; i >= 1; i--) { res = res * i; } Console.WriteLine("
Factorial of "+value+" = "+res); Console.ReadLine(); } } }
Output
Factorial of 5 = 120
Calculate factorial with a while loop
Example
using System; namespace MyApplication { class Factorial { public int display(int n) { int res = 1; while (n != 1) { res = res * n; n = n - 1; } return res; } static void Main(string[] args) { int value = 5; int ret; Factorial fact = new Factorial(); ret = fact.display(value); Console.WriteLine("Value is : {0}", ret ); Console.ReadLine(); } } }
Output
Value is : 120
Calculate factorial using recursion
Example
using System; namespace MyApplication { class Factorial { public int display(int n) { if (n == 1) return 1; else return n * display(n - 1); } static void Main(string[] args) { int value = 5; int ret; Factorial fact = new Factorial(); ret = fact.display(value); Console.WriteLine("Value is : {0}", ret ); Console.ReadLine(); } } }
Output
Value is : 120
Advertisements