Search Your Topic

config
Thursday, 18 May 2017 03:24

Factorial Program in Java

Written by
Rate this item
(0 votes)

Factorial Program in Java: Factorial of n is the product of all positive descending integers. Factorial of n is denoted by n!. For example:

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

Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".

The factorial is normally used in Combinations and Permutations (mathematics).

There are many ways to write the factorial program in java language. Let's see the 2 ways to write the factorial program in java.

  • Factorial Program using loop
  • Factorial Program using recursion

Factorial Program using loop in java

Let's see the factorial Program using loop in java.

 
  1. class FactorialExample{  
  2.  public static void main(String args[]){  
  3.   int i,fact=1;  
  4.   int number=5;//It is the number to calculate factorial    
  5.   for(i=1;i<=number;i++){    
  6.       fact=fact*i;    
  7.   }    
  8.   System.out.println("Factorial of "+number+" is: "+fact);    
  9.  }  
  10. }  

Output:

Factorial of 5 is: 120

Factorial Program using recursion in java

Let's see the factorial program in java using recursion.

 
  1. class FactorialExample2{  
  2.  static int factorial(int n){    
  3.   if (n == 0)    
  4.     return 1;    
  5.   else    
  6.     return(n * factorial(n-1));    
  7.  }    
  8.  public static void main(String args[]){  
  9.   int i,fact=1;  
  10.   int number=4;//It is the number to calculate factorial    
  11.   fact = factorial(number);   
  12.   System.out.println("Factorial of "+number+" is: "+fact);    
  13.  }  
  14. }  

Output:

Factorial of 4 is: 24

 

 

Read 302 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.

Java Training

Facebook