Welcome to Home.

Monday, August 6, 2018

FINDING FACTORIAL OF GIVEN NUMBER | JAVA

Factorial of a number means product of it & it's smaller number to 1. Let's say I have to find out factorial of 5 which implies that.. 5 Factorial = 5 x 4 x 3 x 2 x 1 = 120. It's easy.
In programming language factorial can be achieved by using several techniques. Among them, below example is one .


class Factorial{

      public static void main(String args[]){

          int num = Integer.parseInt(args[0]);                 //take argument as command line

          int result = 1;

          while(num>0){

                result = result * num;

                num--;

          }

          System.out.println("Factorial of Given no. is : "+result);

   }

}

Here in this program,We have taken input as command line, which is stored in integer num also we have created variable result whose default value is set as 1. Now the real part comes. while num value is greater than zero then the code inside the while will execute.

Here, result = result * num;

Let us suppose the given number is 5 . so num = 5;

then, Inside while loop, result = result * num;
                                     i.e result = 1 * 5;
                                      and num--; means num = num -1 ; i.e. num = 5 -1 = 4;

Again , second time inside while loop because num > 0 i.e. 4 >0

                                           result = result * num;
                                      i.e.result = 5 * 4 = 20;
                                       and num --; means num = 4 -1 = 3;

Again....
...
..
.
Eventually, when num =0; it won't go inside while loop and print the value of integer result.


No comments:

Post a Comment