Calculating factorial of number in Java

madhumita_2 avtar
Madhumita Mangaraj

This example below accepts number from user and calculates factorial using while loop and prints it.

import java.util.Scanner;

public class Factorial {

	public static void main(String[] args) {
		int number;
                int factorial = 1;

		Scanner input = new Scanner(;

		//accept input from user
		System.out.println("Enter A Number :");
		number = input.nextInt();

		int i = 1;

		// while loops
		while (i <= number) {
			factorial = factorial * i;

		System.out.println("Factorial is = " + factorial);


Enter A Number :
Factorial is = 720

Sharing is caring!

Did you like what Madhumita Mangaraj wrote? Thank them for their work by sharing it on social media.

madhumita_2 avtar

Madhumita Mangaraj

Java and Android developer

Related articles