Javatpoint Logo
Javatpoint Logo

Factorial Program in Java Using while Loop

The factorial of a number N is the product of all positive descending integers (integers less than or equal to N).

N! = N * (N - 1) ... * 3 * 2 * 1

In this section, we will create Java programs to find the factorial of a number using a while loop and do-while loop.

How to find factorial?

If we say N = 5,

Then the factorial of 5 is represented as 5!

And, 5! = 5 * 4 * 3 * 2 * 1 = 120

Note: The value of 0! is 1, according to the convention for an empty product.

We can find the factorial of a number in Java using the following ways:

Factorial Program Using while Loop

In the while loop, the condition is checked at the beginning of the iteration, and the loop incrementation occurs inside the loop body.

Following are the steps to write a Java program to find factorial of a number using while loop:

  • Declare a variable (int fact) and initialize it with 1.
  • Read a number whose factorial is to be found. Store it in a variable (int num).
  • Set the while loop to the condition (i <= num) where initial value of i = 1.
  • Inside the while loop, multiply the variable fact and variable i, and store the result in variable fact. Increment the loop variable i by 1 (i++).
  • Print the factorial.

Example 1:

FactorialUsingWhileLoop.java

Output:

Factorial Program in Java Using while Loop

Factorial Using while loop and user-defined function

Let's use the while loop in user defined function.

Example 2:

FactorialUsingWhileLoop2.java

Output:

Factorial Program in Java Using while Loop

Factorial Program Using do-while Loop

The factorial program using the do-while loop slightly differs from the while loop. Unlike the while loop, the condition (i <= num) is checked at the end of each iteration.

Example 3:

FactorialUsingDoWhileLoop.java

Output:

Factorial Program in Java Using while Loop

Factorial using do-while loop and user-defined function

Let's use the do-while loop in user defined function.

Example 4:

FactorialUsingDoWhileLoop2.java

Output:

Factorial Program in Java Using while Loop





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA