Factorial program in java (2 different ways)
In this post, you can learn how to find the factorial of any number using java programming language with 2 different approaches.
Approach :-1 "Find factorial using for loop"
package CodeYourslf.allPrograms.factorial;
import java.util.Scanner;
public class byFoorLoop {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int fact = 1;
for(int i = 1; i <= num; i++){
fact = fact * i;
}
System.out.println("The factorial is: "+fact);
}
}
Output :-
Approach :- 2 "find factorial of a number using while loop"
package CodeYourslf.allPrograms.factorial;
import java.util.Scanner;
public class byWhileLoop {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number: ");
int num = sc.nextInt();
int fact = 1;
// int i = 1;
while (num > 0) {
fact = fact * num;
num--;
}
System.out.println("The factorial is: " + fact);
}
}
Code Explanation
Factorial means the product from 1 upto that number.
Ex:- factorial of 5 = 1*2*3*4*5
In programming logic we can find that by using loop concept.
Approach :- 1 Explanation
- I have used for loop to solve this problem.
- here I have started the looo from 1 to num. And assigned the code fact = fact * i , here i will be incremented at each iteration.
And by which each number will multiple one by one to fact and finally the factorial value will store in fact variable.
Approach :-2 Explanation
Here I have used the same concept by in place of for loop I have used while loop to find the factorial of any number in java.
Also read:-
Hey if you learn something new from this post, please share with your friends.
๐ If you have any doubt or any query regarding this topic or anything or, don't feel bad to write it on the comment.