# Java program to calculate the factorial of a given number using while loop

Java Programming Java8Object Oriented Programming

#### Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

#### C++ Programming

238 Lectures 56.5 hours

A factorial of a particular number (n) is the product of all the numbers from 0 to n (including n) i.e. Factorial of the number 5 will be 1*2*3*4*5 = 120.

•  To find the factorial of a given number.
•  Create a variable factorial initialize it with 1.
•  start while loop with condition i (initial value 1) less than the given number.
•  In the loop, multiple factorials with i and assign it to factorial and increment i.
•  Finally, print the value of factorial.

## Example

import java.util.Scanner;
public class FactorialWithWhileLoop {
public static void main(String args[]){
int i =1, factorial=1, number;
System.out.println("Enter the number to which you need to find the factorial:");
Scanner sc = new Scanner(System.in);
number = sc.nextInt();

while(i <=number) {
factorial = factorial * i;
i++;
}
System.out.println("Factorial of the given number is:: "+factorial);
}
}

## Output

Enter the number to which you need to find the factorial:
5
Factorial of the given number is:: 120
Updated on 13-Mar-2020 09:46:41