Java Program to find Factorial of a Number

You are Here:

What is Factorial of a Number?

The factorial of a number n can be defined as the product of all positive numbers less than or equal to n. For example, the factorial of 6 is 1 × 2 × 3 × 4 × 5 × 6 = 720.

Examples

The following table provides few examples of factorial of a number.

NumberFactorialResult
1!11
2!1 × 22
3!1 × 2 × 36
4!1 × 2 × 3 × 424

Note: In Mathematics, factorial of a number is represented by exclamation mark.

Tips: It is recommended to use our online Factorial of a Number calculator for better understanding.

Find a Factorial of a Number

In the following example, we will find a factorial of a number 6.

Example

Java Compiler
public class myClass { public static void main(String[] args) { int num = 6; int i = 1; int factorial = 1; for(i=1; i<=num; i++) factorial *= i; if(num > 0) System.out.format("Factorial of %d: %d\n", num, factorial); else System.out.println("Factorial of 0: 0"); } }

Output

Factorial of 6: 720

Find a Factorial of any Given Number

In the following example, we will find a factorial of any given number.

Example

Java Compiler
import java.util.Scanner; public class myClass { public static void main(String[] args) { Scanner reader = new Scanner(System.in); int i = 1; int factorial = 1; System.out.print("Enter a (int) number: "); int num = reader.nextInt(); for(i=1; i<=num; i++) factorial *= i; if(num > 0) System.out.format("Factorial of %d: %d\n", num, factorial); else System.out.println("Factorial of 0: 0"); } }

Output

Enter a (int) number: 5 Factorial of 5: 120

Reminder

Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.

We are working to cover every Single Concept in Java.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author