Do-While loop in Java
In Java, the do-while
loop is used to execute a block of code at least once before checking the loop condition. It guarantees that the loop body is executed at least once, even if the condition is initially false
.
public class Main {
public static void main(String[] args) {
int count = 0;
do {
System.out.println(count); // Print the current value of count
count++; // Increment count by 1
} while (count < 5); // Continue looping as long as count is less than 5
}
}
Output
0 1 2 3 4
Explanation: Here, we initialize a variable count
and use a do-while
loop to print its value and increment it by 1
on each iteration. The loop continues as long as count
is less than 5
. Even if count
is initially 5
or greater, the loop body executes at least once before the condition is checked.
Do-While loop in Programming
Do-while loop is a control flow statement found in many programming languages. It is similar to the while loop, but with one key difference: the condition is evaluated after the execution of the loop’s body, ensuring that the loop’s body is executed at least once. In this article, we will learn about the basics of Do while loop, its syntax and its usage in different languages.
Table of Content
- What is Do-While Loop?
- Do-While Loop Syntax
- How does Do-While Loop work?
- Do-While Loop in Different Programming Languages
- Do-While loop in Python
- Do-While loop in JavaScript
- Do-While loop in Java
- Do-While loop in C
- Do-While loop in C++
- Do-While loop in PHP
- Do-While loop in C#
- Do-While Use Cases
- Do-While Loop vs Other Loops