JAVA program to find factorial of a given number

JAVA program to find factorial of a given number

This JAVA program is to find factorial of a given number.

For example factorial of 5!= 5*4*3*2*1   hence 5!=120

Logic

We just use a for loop and keep multiplying with each number(i++) till we reach till the number specified(n).

Dry Run of the Program

Take input ‘n’ for which you want to calculate it’s factorial for . Let us take n=4

1st iteration  for(i=1;i<=n;i++)  i.e   for(i=1;i<=4;i++) as n=4

fact=fact*i   i.e fact=1*1 as fact is initalized to 1 and i=1 hence fact=1

2nd iteration  for(i=2;i<=n;i++)  i.e   for(i=2;i<=4;i++)

fact=fact*i   i.e fact=1*2 hence fact=2

3rd iteration  for(i=3;i<=n;i++)  i.e   for(i=3;i<=4;i++)

fact=fact*i   i.e fact=2*3 hence fact=6

4th iteration  for(i=4;i<=n;i++)  i.e   for(i=4;i<=4;i++)

fact=fact*i   i.e fact=6*4 hence fact=24

For loop ends here

We print the output.

Program

import java.util.*;

class factorial {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the no");
        int n = sc.nextInt();
        int i=1,fact=1;
	for(i=1;i<=n;i++)	
	{            
		fact=fact*i;      
	}
 	System.out.println("Factorial of "+n+" = "+fact);
    }
}

Output

Share Me!