d. Rewrite the following program segment using the while loop. Then write the
complete Java code including the while loop to print the factorial of 5.
int factorial = 1, i;
for (i = 1; i <= 5; i++)
factorial *= i;
System.out.println (“Factorial of 5 = + factorial);
Answers
Answer:
Java Program to Find Factorial using For and While loop
BY CHAITANYA SINGH | FILED UNDER: JAVA EXAMPLES
We will write three java programs to find factorial of a number. 1) using for loop 2) using while loop 3) finding factorial of a number entered by user. Before going through the program, lets understand what is factorial: Factorial of a number n is denoted as n! and the value of n! is: 1 * 2 * 3 * … (n-1) * n
The same logic we have implemented in our programs using loops. To understand these programs you should have a basic knowledge of following topics of java tutorials:
For loop in Java
Java – while loop
Example: Finding factorial using for loop
public class JavaExample {
public static void main(String[] args) {
//We will find the factorial of this number
int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++)
{
fact = fact * i;
}
System.out.println("Factorial of "+number