Tutorials

Java Basic Programs


Java Factorial


In this tutorial, our task is:

  • to find the factorial of the given number
  • print the factorial.

Example:

Given number: 7

factorial: 5040

 

How factorial is calculated?

Suppose the number is n.

To calculate the factorial of the number, we multiply a number by every number below it till 1.

n! = n*(n-1)*(n-2)*.....*1

 

Going by above formula,

7! = 7*6*5*4*3*2*1 = 5040

 

Java program to find factorial

Given below is the java program to find factorial of the given number.


public class factorial {

      public static void main(String[] args) {

            int num = 7;
            int fact = 1;
           
            for(int i= num; i>0; i--){

                  fact = fact*i;

            }

            System.out.println(fact);

      } 

}

 OUTPUT:

5040

 

How the above code works?

This program simply demonstrates the use of loops. 

We use for loop to accomplish our task of calculating factorial of given number.

 

Number whose factorial is to be found is 7. We have hardcoded this value. You can use scanner to let user enter value of his choice.

A temporary variable fact is assigned initial value of 1.

1st for loop iteration: i=7; 7>0 so control enters loop,

fact = 1*7 = 7  (fact=1 and i=7)

Now i-- decreases the value of i by 1, so i = 6

2nd for loop iteration: i=6; 6>0 so control enters loop,

fact = 7*6 = 42 (fact=7 and i=6)

Now i-- decreases the value of i by 1, so i = 5

3rd for loop iteration: i=5; 5>0 so control enters loop,

fact = 42*5 = 210 (fact=42 and i=5)

Now i-- decreases the value of i by 1, so i = 4

4th for loop iteration: i=4; 4>0 so control enters loop,

fact = 210*4 = 840 (fact=210 and i=4)

Now i-- decreases the value of i by 1, so i = 3

5th for loop iteration: i=3; 3>0 so control enters loop,

fact = 840*3 = 2520 (fact=840 and i=3)

Now i-- decreases the value of i by 1, so i = 2

6th for loop iteration: i=2; 2>0 so control enters loop,

fact = 2520*2 = 5040 (fact=2520 and i=2)

Now i-- decreases the value of i by 1, so i = 1

7th for loop iteration: i=1; 1>0 so control enters loop,

fact = 5040*1 = 5040 (fact=5040 and i=1)

Now i-- decreases the value of i by 1, so i = 0

8th for loop iteration: i=0; 0>0 is false so for loop terminates the operation.

We get final value of fact = 5040

 



Please Share this page
Views : 78
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!