C# factorial


To calculate factorial in C#, you can use while loop and loop through until the number is not equal to 1.

Here n is the value for which you want the factorial −

int res = 1;
while (n != 1) {
   res = res * n;
   n = n - 1;
}

Above, let’s say we want 5! (5 factorial)

For that, n=5,

Loop Iteration 1 −

n=5
res = res*n i.e res =5;

Loop Iteration 2 −

n=4
res = res*n i.e. res = 5*4 = 20

Loop Iteration 3 −

n=3
res = res*n i.e. res = 20*3 = 60

Example

In this way, all the iterations will give the result as 120 for 5! as shown in the following example.

Live Demo

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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 19-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements