About Lesson
- Do-while loop: A do-while loop is similar to a while loop, but the block of code within the loop is executed at least once, even if the
condition
is false. The basic syntax of a do-while loop is as follows:
do {
// code to execute repeatedly
} while (condition);
Here, the block of code within the curly braces is executed first, and then the condition
is evaluated. If the condition
is true, the loop will continue to execute the block of code within the curly braces.
For example, consider the following code that uses a do-while loop to print the numbers from 1 to 5:
java
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
In this case, the block of code within the curly braces is executed first, and then the condition
is evaluated. Since i
is less than or equal to 5, the loop will continue to execute the block of code.