Home » Blog » Find Factorial With User Input – Java

Find Factorial With User Input – Java

In this tutorial, you can learn how to use loops and operators to perform various tasks. This tutorial will give you insight of what is factorial and how we can calculate it.

Concept Description With Example

The factorial of a positive integer number n , denoted by n!, is the product of all positive integers less than or equal to n.

Scanner is the class in java.util package used for obtaining input of the primitive types like int, float etc. To create the object of Scanner class, we usually pass the predefined object System.in, which represent the standard input system. In this we are using nextInt() method of which takes Integer Value. There are different methods for different data types like nextBoolean(), nextByte(), nextDouble(), nextLine() etc.

Here while loop is executed from 1 to n (number entered by the user or the number for which find the factorial). The all numbers from 1 to n is multiplied and the final Factorial number is obtained.

import java.util.*;
public class fact
{
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int f=1,no,i=1;
		System.out.println("***Factorial***");
		System.out.println("Enter Number for find factorial");
		no=sc.nextInt();
		while(no>=i)
		{
			f=f*i;
			i=i+1;
		}
		System.out.println("Factorial of " + no + " is = " + f);
	}
}

Here is the OutPut

***Factorial***

Enter Number for find factorial
5

Factorial of 5 is = 120

Leave a Reply

Your email address will not be published.