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 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

No comments:

Post a Comment

Floyd Triangle

Note- Floyd Triangle is like 1 2 3 4 5 6 7 8 9 10 ------------ import java.util.Scanner; public class FloydTria...

Popular Post