Web Analytics

While & Do-While Loops

Beginner ~15 min read

While for loops are great when you know the number of iterations, while loops are perfect when you want to loop until a condition changes.

The while Loop

It checks the condition before entering the loop block. If the condition is false initially, the code never runs.

while (condition) {
    // Code to execute
    // Update variables
}

The do-while Loop

It checks the condition after executing the block. This guarantees the code runs at least once.

do {
    // Code to execute
} while (condition);
Use Case: Use do-while for user menus (display menu, get choice, repeat if invalid). You always want to show the menu at least once.
Output
Click Run to execute your code

The Infinite Loop Trap

If you forget to update the condition variable inside the loop, it might never end!

int i = 0;
while (i < 5) {
    System.out.println(i);
    // Missing i++ here! Loop runs forever.
}

Summary

  • While Loop: Checks condition first. Might run 0 times.
  • Do-While Loop: Checks condition last. Runs at least 1 time.
  • Always ensure your loop has a way to exit (avoid infinite loops).