StackTips

Calculating factorial of number in Java

madhumita avtar

Written by

Madhumita,  1 min read,  2.59K views, updated on Sept. 17, 2023

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(System.in);

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

		int i = 1;

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

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

Output

Enter A Number :
6
Factorial is = 720

Beginner's Guide to Java Collections

This course covers the fundamentals of java collections framework covering different data structures in Java to store, group, and retrieve objects.

>> CHECK OUT THE COURSE
madhumita avtar

Madhumita

Java and Android developer

Related posts

Let’s be friends!

🙌 Stay connected with us on social media for the latest updates, exclusive content, and more. Follow us now and be part of the conversation!