Java Program to find the Factorial of a Number

Here is a Java Program to find the factorial of a number.

public class Factorial {

    public void factorial(int n) {
        int fact = 1;
        for (int i = 1; i <= n; i++) {
            fact = fact * i;
        System.out.println("Factorial is " + fact);

The method factorial() takes an integer n, the number whose factorial we should find. fact is initailised to 1. The loop runs from 1 to n. In each iteration, we multiply fact with i. So, at the end of the loop, fact will becomes 1 * 2 * 3 * … n which is the factorial of the number.

Sample Execution :

Input :
n = 7

Output :
Factorial is 5040

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>