Tuesday, February 12, 2019

Factorial Program in Java with examples.

Factorial Program in Java

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 shrieks".
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

No comments:

Post a Comment

Java String Interview Questions and Answers

1) What is String in Java? Is String is data type? String in Java is not a primitive data type like int, long or double. The string is a ...