Tuesday, 22 November 2016

Factorial of a given number

Factorial of a number is the product of all positive descending integers. Factorial of n is denoted by n!.
For example,

3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1  = 24
5! = 5 * 4 * 3 * 2 * 1 = 120

Here you have to get the number from command line argument. The logic to find the factorial of a number is given below.


PROGRAM
class Factorial {

 public static void main(String[] args) {

  int fact=1,no;
  no = Integer.parseInt(args[0]);
  
  System.out.print("Factorial of "+no+" is ");
  
  while(no > 0) {
   
   fact = fact * no;
   no--;
  }
  System.out.println(fact);
 }
}
OUTPUT
C:\>javac Factorial.java
C:\>java Factorial 4
Factorial of 4 is 24

No comments:

Post a Comment