Implementing the factorial function n! - Java Language Basics

Java examples for Language Basics:while

Description

Implementing the factorial function n!

Demo Code

public class Main {
  static int factorial(int n) {
    int result = 1;

    while (n > 0) {
      result *= n; // similar to result=result*n;
      n--;/*from   w  ww .ja va  2s  . co  m*/
    }
    return result;
  }

  public static void main(String[] args) {
    System.out.println("6!=" + factorial(6));
  }
}

Result


Related Tutorials