Factorial Program Using Loop in Java

9/3/2021
All Articles

#Factorial Program Using Loop in Java  #java #loop #javaFactorial

Factorial Program Using Loop in Java

Factorial Program Using Loop in Java

Factorial Program in scala : Factorial of n is the product of all positive descending integers like (1,2,3...). 
Factorial of n number is denoted by n!. For example of scala factorial program:
 
4! = 4*3*2*1 = 24  
5! = 5*4*3*2*1 = 120 
 
 

Let's See the Factorial Program Using Loop in Java.

This program, we define a function factorial that calculates the factorial of a given integer n . 
The base case for the recursive function is when n is 0 or 1, in which case the factorial is 1. 
Otherwise, the function calls itself with n - 1 and multiplies the result by n and  we got expected result.
 

Example 1 without recursion :

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);   
}
 

Example 2 with recursion :

  public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * factorial(n - 1); // recursion call
        }
    }
 

​Conclusion :

In the main method, we call the factorial function with recursion way and we have another example without recursion.

This Solution is provided by Shubham mishra

This article is contributed by Developer Indian team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Also folllow our instagram , linkedIn , Facebook , twiter account for more

Article