C# factorial

CsharpServer Side ProgrammingProgramming

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
raja
Published on 24-Jul-2018 15:31:10
Advertisements