Skip to main content

Command Palette

Search for a command to run...

Difference between while loop & do while loop in dart

Published
•2 min read•View as Markdown
Difference between while loop & do while loop in dart
P

I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.

In Dart, both while and do...while loops are used for repetitive execution of code based on certain conditions, but they differ in how they evaluate their conditions and when they execute their block of code.

Here are the key differences between the while loop and the do...while loop in Dart:

  1. Condition Evaluation:

    • In a while loop, the condition is evaluated before the loop body is executed. If the condition is initially false, the loop body may never execute.

    • In a do...while loop, the condition is evaluated after the loop body is executed at least once. This means that the loop body is executed at least once, regardless of whether the condition is true or false.

  2. Execution Order:

    • In a while loop, if the condition is false initially, the loop body is not executed at all.

    • In a do...while loop, the loop body is executed at least once, and then the condition is checked. If the condition is false after the first iteration, the loop terminates.

Here's a simple comparison to illustrate the difference:

// while loop example
var i = 0;
while (i < 0) {
  print('This will not be printed');
  i++;
}

// do...while loop example
var j = 0;
do {
  print('This will be printed at least once');
  j++;
} while (j < 0);

In the while loop, the condition i < 0 is false initially, so the loop body is never executed.

In the do...while loop, the loop body is executed once before the condition j < 0 is checked. Since j starts at 0, the loop body executes once, even though the condition is false.

In summary, use a while loop when you want to execute the loop body based on a condition that might be false initially, and use a do...while loop when you want to ensure that the loop body is executed at least once before checking the condition.

More from this blog

Parth Chauhan's blog

87 posts

Learner, Accountant, Marketer, Programmer.