We will write three java programs to find factorial of a number. 1) using for loop 2) using while loop 3) finding factorial of a number entered by user. Before going through the program, lets understand what is factorial: Factorial of a number n is denoted as n!
and the value of n!
is: 1 * 2 * 3 * … (n-1) * n
The same logic we have implemented in our programs using loops. To understand these programs you should have a basic knowledge of following topics of java tutorials:
Example: Finding factorial using for loop
public class JavaExample { public static void main(String[] args) { //We will find the factorial of this number int number = 5; long fact = 1; for(int i = 1; i <= number; i++) { fact = fact * i; } System.out.println("Factorial of "+number+" is: "+fact); } }
Output:
Factorial of 5 is: 120
Example 2: Finding Factorial using while loop
public class JavaExample { public static void main(String[] args) { //We will find the factorial of this number int number = 5; long fact = 1; int i = 1; while(i<=number) { fact = fact * i; i++; } System.out.println("Factorial of "+number+" is: "+fact); } }
Output:
Factorial of 5 is: 120
Example 3: Finding factorial of a number entered by user
Program finds the factorial of input number using while loop.
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { //We will find the factorial of this number int number; System.out.println("Enter the number: "); Scanner scanner = new Scanner(System.in); number = scanner.nextInt(); scanner.close(); long fact = 1; int i = 1; while(i<=number) { fact = fact * i; i++; } System.out.println("Factorial of "+number+" is: "+fact); } }
Output:
Enter the number: 6 Factorial of 6 is: 720
Leave a Reply