While vs Do-While Loop

 

                                                         While Vs Do-While Loop

Comparison Basis

While Loop

Do-While Loop

Definition

Executes a block of code as long as the condition is true

Executes a block of code at least once, and then repeats as long as the condition is true

Condition Evaluation

Before entering the loop body

After executing the loop body

Execution Guarantee

May not execute if the condition is false initially

Executes at least once regardless of the condition

Syntax

while (condition) { // code }

do { // code } while (condition);

Use Case

When the loop should run only if the condition is initially true

When the loop must run at least once

Initial Check

Condition checked before execution

Condition checked after execution

Example

while (i < 5) { i++; }

do { i++; } while (i < 5);

Comments