What is the Difference Between while and do while loop?

🆚 Go to Comparative Table 🆚

The main difference between a while loop and a do-while loop is the way they check the condition for executing the loop. Here are the key differences between while and do-while loops:

  1. Execution: A while loop checks the condition before executing the loop. If the condition is false, the loop statements are executed zero times. On the other hand, a do-while loop checks the condition after executing the loop. The loop body is executed at least once, even if the condition is false.
  2. Control Flow: A while loop is an entry-controlled loop, meaning the condition is checked before entering the loop. If the condition is false, the loop is not executed. A do-while loop is an exit-controlled loop, meaning the condition is checked after the loop has been executed.
  3. Condition Initialization: In a while loop, the counter variable is initialized before the loop, and the loop continues as long as the condition holds true. In a do-while loop, the counter variable can be initialized before and after the loop, allowing for multiple initializations.

In summary, you should use a while loop when you want to execute a block of code zero or more times, depending on a condition. A do-while loop should be used when you want to execute a block of code at least once, and then continue executing it zero or more times, depending on a condition.

Comparative Table: while vs do while loop

The main differences between while and do-while loops are:

Feature While Loop Do-While Loop
Condition Check Condition is checked before executing the statement(s). If the condition is false, the statement(s) is executed zero times. The statement(s) is executed at least once, then the condition is checked. If the condition is false, the statement(s) is executed only once.
Syntax while(condition) do { statements } while(condition);
Semicolon No semicolon at the end of while. Semicolon at the end of while.
Variable Initialization Variable in the condition is initialized before the execution of the loop. Variable in the condition may be initialized before or within the loop.
Control Entry controlled loop. Exit controlled loop.

In summary, a while loop checks the condition before executing the statement(s) and may execute the statement(s) zero times if the condition is false. In contrast, a do-while loop executes the statement(s) at least once and then checks the condition, which may lead to the statement(s) being executed only once if the condition is false.