Java Program to Find Factorial of a Number

In this Java program, we’ll learn how to find the factorial of a number in your Java program.  

How to Find the Factorial of a Number? 

Example 1: using loop 

RUN CODE SNIPPET
class Main{   
 public static void main(String args[]){   
  int i,fact=1;   
  int number=6;    
  for(i=1;i<=number;i++){     
      fact=fact*i;     
  }     
  System.out.println("Factorial of "+number+" is: "+fact);     
 }   
}

OUTPUT

Factorial of 6 is: 720

Example 2: using recursion  

RUN CODE SNIPPET
class Main{   
 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=5;     
  fact = factorial(number);    
  System.out.println("Factorial of "+number+" is: "+fact);     
 }   
}

OUTPUT 

Factorial of 5 is: 120

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Java is a popular programming language that is used to develop a wide range of applications. If you are a...
  • Java
  • March 6, 2023
Java is a programming language and computing platform that is used to create various types of applications. It is used...
  • Java
  • March 6, 2023
In this post, you’ll learn how to download and install JUnit in Eclipse so that you can use in your...
  • Java
  • October 9, 2022