C# Factorial

PHPz
Release: 2023-08-28 16:21:02
forward
1342 people have browsed it

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;
}
Copy after login

Above, assuming we want 5! (5 factorial)

For this, n=5,

Loop iteration 1 -

n=5
res = res*n i.e res =5;
Copy after login

Loop iteration 2 -

n=4
res = res*n i.e. res = 5*4 = 20
Copy after login

Loop iteration 3 -

n=3
res = res*n i.e. res = 20*3 = 60
Copy after login

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();
      }
   }
}
Copy after login

Output

Value is : 120
Copy after login

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

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template