Factorial Program in Java Using while LoopThe 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 LoopIn 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:
Example 1:FactorialUsingWhileLoop.java Output: Factorial Using while loop and user-defined functionLet's use the while loop in user defined function. Example 2: FactorialUsingWhileLoop2.java Output: Factorial Program Using do-while LoopThe 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 using do-while loop and user-defined functionLet's use the do-while loop in user defined function. Example 4: FactorialUsingDoWhileLoop2.java Output:
Next TopicFrugal Number in Java
|