C# Factorial

PHPz
PHPzforward
2023-08-28 16:21:021384browse

C# 阶乘

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

Here n is the value of you want the factorial -

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

Above, assuming we want 5! (5 factorial)

For this, 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, the result of all iterations is 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

The above is the detailed content of C# Factorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete