Java Programming | Calculating factorial of number

Introduction

This is a tutorial for calculating factorial of number using while loop in java. The program is given below that takes the number from user and calculates factorial and prints it. The program is not extendable. Go enjoy the program. Lets begin………..

What’s a factorial?

You may have studied factorial in your maths book. The factorial is usually denoted by n! .i.e 5! is factorial of 5. The factorial is calculated as:- 5! =1x2x3x4x5.

Program for calculating factorial of number in java.


//import Scanner as we require it.
import java.util.Scanner;

// the name of our class its public
public class Factorial {
//void main
public static void main (String[] args)
{
//declare int
int i=1,no,fact=1;

//Declare input as scanner
Scanner input = new Scanner(System.in);

//Take input
System.out.println("Enter Number :");
no = input.nextInt();

//while loops
while(i<=no)
{
fact=fact*i;
i++;
}

System.out.println("Factorial = "+fact);
}
}

Output

Enter Number :
5
Factorial = 120

How does it work

  1. You enter the number.
  2. The factorial is calculated using while loop
  3. The factorial is printed.

Extending it

The program cannot be extended.

Explanation.

  1. Import the Scanner.
  2. Declare the class as public
  3. Add the void main function
  4. Add system.out.println() function with the message to enter number.
  5. Declare input as Scanner.
  6. Take the inputs and save it in variables.
  7. Add a loop and calculate the factorial.
  8. Add system.out.println() function to print factorial.

At the end.

You learnt creating the Java program for Calculating factorial of number. So now enjoy the program.

Please comment on the post and share it.
And like it if you liked.

Sharing options: