Contenido del Curso
Principios Básicos de Java
Principios Básicos de Java
Loop Do-While
What is the difference between while and do-while?
The do-while
loop is another type of loop in Java that is similar to the while
loop. However, it has one important difference: the condition is checked at the end of each iteration. This means the code block will always execute at least once before evaluating the condition.
Here's the basic syntax of the do-while
loop:
Main
do { // Code block } while (condition);
Here are some key points to keep in mind about the do-while
loop:
-
Execution Flow: The code block is executed first, and then the condition is checked. If the condition is true, the loop continues to the next iteration. If the condition is false, the loop terminates, and the program continues with the next statement after the loop;
-
Guaranteed Execution: Since the code block is executed before the condition check, the
do-while
loop is useful when you want to ensure that the code block runs at least once, regardless of the initial condition; -
Variable Scope: Variables defined within the code block of a
do-while
loop have a scope limited to that code block. They cannot be accessed outside the loop; -
Use Cases: The
do-while
loop is commonly used when you want to prompt the user for input at least once and then continue the loop based on a condition. It is also useful when iterating through a list of elements, ensuring that the loop runs at least once, even if it is empty.
Let's look at a simple example of usage and compare the results of a while
loop and a do-while
loop on a very basic example:
main
package com.example; public class Main { public static void main(String[] args) { // do-while loop do { System.out.println("Do-while loop executed successfully"); } while (1 < 0); } }
Veamos un ejemplo sencillo de uso y comparemos los resultados de un loop while
y un loop do-while
en un ejemplo muy básico:
main
package com.example; public class Main { public static void main(String[] args) { // do-while loop do { System.out.println("Do-while loop executed successfully"); } while (1 < 0); } }
bucle while
:
1. What will be the output of the code?
2. What will be the output of the code?
¡Gracias por tus comentarios!