Writing Factorial program in java

Thread Programming In java
Socket Programming in Java

In mathematics, the factorial of any non-negative number let’s say X, is denoted by X! , which is equal to the product of all positive integers less than or equal to X. i.e.
Let the non-negative integer be 5, then factorial of 5 is denoted by 5! = 5 * 4 * 3 * 2 * 1
From the above example we can now introduce factorial general term as:

N ! = N * ( N – 1 ) !

Factorial of zero (0!) is 1, it is considered as empty product.
Ready to make a factorial program in java? Here’s the code:

import java.util.Scanner; // Scanner class used to take input

class Factorial
	public static void main (String[] args)

		Scanner n = new Scanner(System.in); //'n' as a Scanner class object with "System.in" as constructor argument

		System.out.print("Enter Number :");

		int inputNumber = n.nextInt(); // n.nextInt() function takes integer input

		int factorialResult = 1; // initialize factorialResult with value 1

		while (inputNumber>=0)
			if (inputNumber==0)
			factorialResult = factorialResult * 1;
			factorialResult = inputNumber * factorialResult;
		} //end loop

		System.out.println("Factorial is : "+factorialResult);

	} // end main

} // end Factorial class

This program calculates the factorial of the given number. Every time loop traverses, it assures that the given number is not less than zero, multiplies each number with its one decrement and store it for the next. Finally the main function ends with displaying the result calculated.

Output is:


Thread Programming In java
Socket Programming in Java

Leave a Reply