Use for statement to calculate factorial with iterative method. - Java Object Oriented Design

Java examples for Object Oriented Design:Method

Description

Use for statement to calculate factorial with iterative method.

Demo Code

public class Main
{
   // recursive declaration of method factorial   
   public static long factorial(long number)
   {//from   w  w  w  .  ja va2s  .  co m
      long result = 1;

      // iterative declaration of method factorial
      for (long i = number; i >= 1; i--)
         result *= i;

      return result;
   } 

   // output factorials for values 0-10
   public static void main(String[] args)
   {
      // calculate the factorials of 0 through 10
      for (int counter = 0; counter <= 10; counter++)
         System.out.printf("%d! = %d%n", counter, factorial(counter));
   }
}

Result


Related Tutorials