- One of the famous java interview program for freshers is finding factorial of a number using java program
- Calculating the factorial of a number using java example program with recursion.
- Factorial number means multiplication of all positive integer from one to that number.
- n!=1*2*3.......*(n-1)*n.
- Here ! represents factorial.
- Two factorial: 2!= 2*1=2
- Three factorial: 3!= 3*2*1=6.
- Four factorial : 4!= 4*3*2*1=24.
- Five factorial: 5!= 5*4*3*2*1=120.
- Six factorial: 6!= 6*5*4*3*2*1=720
- Seven factorial: 7!= 7*6*5*4*3*2*1=5040
- Eight factorial: 8!= 8* 7*6*5*4*3*2*1=40320.
- By using loops we can find factorial of given number.
- Lets how can we find factorial of a number using java program without recursion.
Program #1: Java program to find factorial of a number using for loop
- package interviewprograms.instanceofjava;
- import java.util.Scanner;
- public class FactiorialProgram {
- public static void main(String args[]){
- Scanner in = new Scanner(System.in);
- System.out.println("Enter a number to find factorial");
- int n= in.nextInt();
- int fact=1;
- for (int i = 1; i < n; i++) {
- fact=fact*i;
- }
- System.out.println("Factorial of "+n+" is "+fact);
- }
- }
Output:
- Enter a number to find factorial
- 5
- Factorial of 5 is 120
Program #2: Java program to find factorial of a number using recursion.
- package interviewprograms.instanceofjava;
- import java.util.Scanner;
- public class FactiorialProgram {
- public static void main(String args[]){
- Scanner in = new Scanner(System.in);
- System.out.println("Enter a number to find factorial");
- int n= in.nextInt();
- int fact=1;
- for (int i = 1; i < n; i++) {
- fact=fact*i;
- }
- System.out.println("Factorial of "+n+" is "+fact);
- }
- }
Output:
- Enter a number to find factorial
- 5
- Factorial of 5 is 120
Program #3: Java program to find factorial of a number using recursion (Eclipse)
No comments