0 likes | 63 Views
In Java, the do-while loop is a control flow statement that executes a block of code repeatedly until a specified condition becomes false. In the do-while loop, we execute the statement first before checking the given condition or expressions.So the do block will execute at least once whether the condition is true or false.<br>for more free learning visit:<br>https://quipoin.com/view/Java/do-while
E N D
Do-While Loop do-while loop in Java
Overview • In Java, the do-while loop is a control flow statement that executes a block of code repeatedly until a specified condition becomes false. • In the do-while loop, we execute the statement first before checking the given condition or expressions. • So the do block will execute at least once whether the condition is true or false.
Program public class DoWhileLoop { public static void main(String[] args) { int i = 1; do { System.out.println(i); i++; } while (i <= 5); } }
Features: • Always Executes the Block of Code at Least Once: • The primary distinction of the do-while loop is that it always executes the code block at least once, even if the condition is initially false. This is because the condition is checked after the first execution. • Post-Test Loop: • The condition is checked after the execution of the code block. This makes it a post-test loop, as opposed to the while loop, which is a pre-test loop where the condition is checked before the code block is executed. • Flexible Structure: • The do-while loop has a flexible structure that allows for easy implementation of repetitive tasks. The loop body is enclosed in curly braces, and the do keyword indicates the beginning of the loop. • Simplifies Control Flow: • It simplifies control flow in scenarios where you want to ensure that a certain block of code is executed at least once, regardless of the initial condition. This can be useful in situations such as user input validation.