Search

Factorial Program in Java || Java Programs

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


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


Factorial Program using loop in java


Program -


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

Output -

Factorial of 5 is: 120

Factorial Program using recursion in java


Program -


class FactorialExample2{  
 static int factorial(int n){    
 if (n == 0)    
 return 1;    
 else 
 return(n * factorial(n-1));    
 }    
 public static void main(String args[]){  
 int i,fact=1;  
 int number=4;//It is the number to calculate factorial   
  fact = factorial(number);   
  System.out.println("Factorial of "+number+" is: "+fact);    
 }  
}  

Output -

Factorial of 4 is: 24


Related Posts

See All

How to Print Pattern in Java || Java Programs

Java pattern program enhances the coding skill, logic, and looping concepts. It is mostly asked in Java interview to check the logic and thinking of the programmer. We can print a Java pattern program

How to Generate Random Number in Java || Java Programs

In real world projects, we often required to generate random numbers while we develop applications. Many applications have the feature to generate numbers randomly, such as to verify the user many app

Armstrong Number in Java || Java Programs

Armstrong Number in Java: A positive number is called armstrong number if it is equal to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc. Let's try to understand why 153 is an

  • Facebook
  • Instagram
  • LinkedIn
  • 1024px-Telegram_logo.svg
  • download
  • YouTube
  • Google Play