java

Factorial Program In Java In 2 Different Ways

In this tutorial, we are going to see how to calculate the factorial of a number in Java. Before moving on to the program, let’s first understand what is a factorial: the factorial of a number n is denoted by n! and the value of n! is: 1 * 2 * 3 *… (n-1) * n. There are two ways to find a factorial of a given number, using the for loop or recursion. Remember that the stop value must be the number entered by the user + 1.

The same logic we implemented in the programs below.
 

Method 1: Calculate the factorial using the for loop
public class Main {
	public static void main(String args[]){
		int i, f = 1;
		//the number whose factorial we want to calculate
		int nbr = 3;
		for(i=1; i <= nbr; i++){ 
			f = f * i;  
		}  
		System.out.println("Factorial of "+nbr+" is: "+f);  
	}
}

Output:

Factorial of 3 is: 6

 
[st_adsense]  

Method 2: Calculate the factorial using recursion
public class Main{
	
	static int fact(int n){
		if (n == 0)  
			return 1;  
		else  
			return(n * fact(n-1));  
	}  
	
	public static void main(String args[]){
		int i, f = 1;
		//the number whose factorial we want to calculate
		int nbr = 3;
		f = fact(nbr); 
		System.out.println("Factorial of "+nbr+" is: "+f);
	}
}

Output:

Factorial of 3 is: 6
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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