Back to: Java Tutorials
The do-while
loop is a type of loop that is similar to the while
loop, but with one key difference: the loop condition is checked at the end of each iteration, rather than at the beginning. This means that the loop will always execute at least once, regardless of whether the condition is initially true or false.
Here is the syntax for a do-while
loop in Java:
do {
// code to be executed
} while (condition);
The loop starts with the keyword do
, followed by a block of code to be executed inside the loop. After the code block, the loop condition is specified using the while
keyword, followed by the condition in parentheses.
Here is an example of using a do-while
loop in Java to calculate the factorial of a given number:
import java.util.Scanner;
/**
* An example of using a do-while loop in Java to calculate the factorial of a
* given number
*
* @author Mamun Kayum
*
*/
public class FactorialDoWhileLoop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, i = 1, factorial = 1;
System.out.print("Enter a number: ");
n = input.nextInt();
do {
factorial *= i;
i++;
} while (i <= n);
System.out.println("The factorial of " + n + " is " + factorial);
}
}
In this example, the user is asked to enter a number, and the program calculates the factorial of that number using a do-while
loop. The loop starts with an initial value of i = 1
and factorial = 1
. Inside the loop, the code multiplies factorial
by i
and increments i
by 1. The loop continues until i
is greater than n
.
The loop condition i <= n
is checked at the end of each iteration, which guarantees that the loop will execute at least once, even if the user enters a number less than or equal to zero.
When you run this code and enter a positive integer, it will calculate the factorial of that number and print the result. For example, if you enter 5, the program will calculate the factorial of 5, which is 5 x 4 x 3 x 2 x 1 = 120.
Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.
Follow us on social media
Follow Author