Post-Test Loops

Do-While Loop Step by Step

Guaranteed minimum single execution and post-evaluated iteration in C, Java, JS, and Python.

SLIDE 1 / 6

1. At Least Once Guarantee

Unlike `while`, the `do-while` loop executes its code block at least once before checking the condition.

STEP ORDER
1. Ejecutar CuerpoGarantizado
2. Evaluar CondiciónPost-Prueba

2. C: do { ... } while(cond);

En C requiere punto y coma final `;` tras la condición `while(cond);`.

do_while.c
int opcion;
do {
    printf("Ingrese opcion (0 para salir): ");
    scanf("%d", &opcion);
} while (opcion != 0);

3. Java: Menús Interactivos

Ideal para validación de entrada de usuario y menús interactivos donde se necesita al menos una interacción inicial.

DoWhileTest.java
int input;
do {
    input = readInput();
} while (input < 0);

4. JavaScript: do { ... } while

JS soporta `do-while` nativo para reintentos de red o promesas con al menos un intento primario.

do_while.js
let intentos = 0;
do {
    intentos++;
    console.log(`Intento ${intentos}`);
} while (intentos < 3);

5. Python: Emulación de do-while (while True + break)

Python NO tiene `do-while` nativo. Se emula usando `while True:` con una condición `if ...: break` al final del cuerpo.

do_while_emulated.py
while True:
    user_input = input("Password: ")
    if user_input == "secret":
        break # Post-condición de salida

6. Comparative Simulator

Observe the difference when initial condition is false:

While Loop (Pre-prueba)
Ejecuciones del cuerpo: 0 veces (Se saltea inmediatamente)
Do-While Loop (Post-prueba)
Ejecuciones del cuerpo: 1 vez (Garantizado)