Java Program to calculate factorial of a number

Input

NA, Since the value for number is set to 5 in the program itself

Program Code

package programs.java4newbie.com;

/*
This Program calculates the factorial of a number using the formula n!= n*(n-1)*(n-2)...1
*/

public class Factorial {

public static void main(String[] args) {
int factorial = 1 ; //Initialise factorial variable to 1

int number = 5;

for(int counter = number; counter >=1 ; counter--)
{
factorial = factorial * counter;
}

/*
* 1st Loop: counter = 5
* 2nd Loop: counter = 4
* 3nd Loop: counter = 3
* 4nd Loop: counter = 2
* 5nd Loop: counter = 1
*/

// factorial of 5 is 5*4*3*2*1 = 120
System.out.println("Factorial of the number is " + factorial);
}
}

Output

Factorial of the number is 120

Leave a comment