Factorial in Java


To find the factorial of a number. Factorial is the process multiplying all the natural numbers below the given number.

The using for the for loop. A for loop is a repetition control structure which allows us to write a loop that is executed a specific number of times. The three components of the for loop (separated by ;) are variable declaration/initialization (i = 0), the condition ( i < 100), and the increment statement ( i++).

Source Code

import java.util.Scanner;
 
public class Factorial {
    public static void main(String args[])
    {
        //1.Write a program to find the factorial of given number.
        Scanner in =new Scanner(System.in);
        System.out.println("Enter The Number : ");
        int n=in.nextInt();//5
        int f=1;
        for(int i=1;i<=n;i++)
        {
            f=f*i;
        }
        System.out.println("Factorial of "+n+" is "+f);
    }
}
 

Output

Enter The Number :
5
Factorial of 5 is 120
To download raw file Click Here

Basic Programs