Factorial number program in Java

In this section you will learn how to find a factorial of given number. In mathematic term factorial of non-negative integer, is multiplication of all integers.

Example of factorial number:

Formula:- n! = n x (n - 1) x (n - 2) x .... x 1

5! = 5 x 4 x 3 x 2 x 1 = 120.

4! = 4 x 3 x 2 x 1 = 24.

What is scanner function?

Scanner function is use to take the input from user in java.

How program will work?

Program of factorial in Java


	import java.util.Scanner;

	class Factorial
	{
		public static void main(String arg[])
		{
			int n,i,fact=1;
			Scanner sc = new Scanner(System.in);
			System.out.println("ENTER A NUMBER:- ");
			n = sc.nextInt();
			for(i=1; i<=n; i++)
			{
				fact=fact*i;
			}
			System.out.println("FACTORIAL IS:- "+fact);
		}
	}

Output:


	ENTER A NUMBER:- 5
	FACTORIAL IS:- 120

Advertisment

Post Your Comment