A program to find factorial for an integer data-type using while loop in JAVA
Algorithm for Factorial
Step 1: Start
Step 2: Read a number n
Step 3: Initialize variables: i = 1, result = 1
Step 4: if i <= n go to Step 4 otherwise go to Step 7
Step 5: Calculate result = result * i
Step 6: Increment the i by 1 (i = i + 1) and go to Step 3
Step 7: Display result
Step 8: Stop
Working example
/**
* Factorial for N using WHILE loop
*/
class FactorialDemoUsingWhileLoop
{
public static void main(String[] args)
{
int i = 1, result = 1, n = 5;
while (i <= n)
{
// System.out.println("I: " + i);
// System.out.println("Result B4: " + result);
result *= i;
// System.out.println("Result After: "+ result);
i += 1;
}
System.out.println("Factorial of " + n + ": " + result);
}
}
Output for number 5
Factorial of 5: 120 Related Articles
Deepen your understanding with these curated continuations.
How to Find ASCII Value of a Character in Java: 4 Easy Methods
Master finding ASCII values in Java! Explore 4 different methods including type-casting, brute force, and byte arrays with clear, practical code examples.
Factorial of a Number Using For Loop in Java: Code & Algorithm
Find the factorial of any integer in Java using a for loop. Explore the step-by-step logic, code implementation, and why we initialize the result variable to 1.
A Program to display sum of 1 to 10 numbers using for loop in JAVA
A Program to display sum of 1 to 10 numbers using for loop in JAVA.