- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to calculate the factorial of a given number using while loop
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
Advertisements