Java Program to Find Factorial of a Number using For Loop

  • Write a program in Java 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