Java Program to Find Factorial of a Number using For Loop

Here is a Java program to find factorial of a number using for loop. Given a positive integer N, we have to calculate factorial of N using for loop.

!5 = 1 x 2 x 3 x 4 x 5 = 120
!6 = 1 x 2 x 3 x 4 x 5 x 6 = 720
!0 = 1
The factorial of a integer n, denoted by n!, is the product of all positive integers less than or equal to n.
Factorial does not exist for negative numbers and factorial of 0 is 1. Its most basic occurrence is the fact that there are n! ways to arrange n distinct objects into a sequence.
  • N! = 1*2*3*4*.... *(N-2)*(N-1)*N

Java program to find factorial of a number

In this program we will take N as input from user using Scanner class. Using for loop we will calculate product of all numbers from 1 to N. After calculating value of N! we print it on screen.

package com.tcc.java.programs;

import java.util.*;

public class FactorialLoop {
    public static void main(String args[]) {
        int num, factorial = 1, i;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter an Integer");
        num = in.nextInt();
        
        for (i = 1; i <= num; i++){
            factorial = factorial * i;
        }
        
        System.out.println("!" + num + " = " + factorial);
    }
}
Output
Enter an Integer
5
!5 = 120
Enter an Integer
0
!0 = 1

Recommended Posts
Java Program to Find Factorial of a Number Using Recursion
Java Program to Print Armstrong Numbers Between 1 to N
Java Program to Reverse a Number using Recursion
Java Program to Check Whether a Number is Palindrome or Not
Java Program to Check If a Year is Leap Year or Not
Java Program to Check Perfect Number or Not
Java Program to Check a Number is Prime Number or Not
Java Program to Find Transpose of a Matrix
Java Program to Count Number of Digits in a Number
Java Program to Find Sum of Digits of a Number
Java Program to Find LCM and GCD of Two Numbers
All Java Programs