Factorial Program in Java

In Java, the factorial of a number ‘n’ represents the product of all positive descending integers from ‘n’ down to 1. It is commonly denoted as ‘n!’.

For instance, let’s consider an example to illustrate factorial:

Factorial of 5 (5!) = 5 * 4 * 3 * 2 * 1 = 120.

The factorial is a fundamental concept in mathematics and finds applications in areas such as combinations and permutations. In Java, there are multiple ways to implement a factorial program. Let’s explore two common approaches:

  • Factorial Program using loop
  • Factorial Program using recursion

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

To expand your knowledge on topics like the Java Factorial Program, you can visit the website tutorials.freshersnow.com.