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

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024