Dart Do...While Loop

Execute first, then check condition

🔄 What is Do...While Loop?

Do-while loops execute code at least once, then repeat while a condition is true. Unlike while loops, the condition is checked after execution, guaranteeing the code runs at least one time.


// Simple do-while loop example
void main() {
  int count = 1;
  do {
    print('Count: $count');
    count++;
  } while (count <= 5);
}
                                    

Do...While vs While

▶️

Execute First

Code runs before condition check

do {
  // This runs first
} while (condition);

Guaranteed Execution

Always runs at least once

do {
  print('Runs once');
} while (false);
🔍

Post-condition Check

Condition tested after execution

do {
  // code here
} while (check_condition);
🎯

Perfect for Menus

Great for user interaction loops

do {
  showMenu();
  choice = getInput();
} while (choice != 'exit');

🔹 Basic Do...While Loop

Simple counting example showing guaranteed execution:

void main() {
  int number = 1;
  
  print('Counting with do-while:');
  do {
    print('Number: $number');
    number++;
  } while (number <= 5);
  
  print('Loop finished!');
}

Output:

Counting with do-while:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Loop finished!

🔹 Do...While vs While Comparison

See the difference when condition is initially false:

🔸 While Loop (condition false from start)

void main() {
  int count = 10;
  
  print('While loop:');
  while (count < 5) {
    print('This will not print');
    count++;
  }
  print('While loop finished');
}

🔸 Do-While Loop (same condition)

void main() {
  int count = 10;
  
  print('Do-while loop:');
  do {
    print('This prints once: $count');
    count++;
  } while (count < 5);
  print('Do-while loop finished');
}

Output:

While loop:

While loop finished

Do-while loop:

This prints once: 10

Do-while loop finished

🔹 Menu System Example

Perfect use case for do-while loops - interactive menus:

import 'dart:io';

void main() {
  String choice;
  
  do {
    print('\n=== Calculator Menu ===');
    print('1. Add');
    print('2. Subtract');
    print('3. Multiply');
    print('4. Divide');
    print('5. Exit');
    print('Enter your choice (1-5):');
    
    choice = stdin.readLineSync() ?? '';
    
    switch (choice) {
      case '1':
        print('You selected Addition');
        break;
      case '2':
        print('You selected Subtraction');
        break;
      case '3':
        print('You selected Multiplication');
        break;
      case '4':
        print('You selected Division');
        break;
      case '5':
        print('Goodbye!');
        break;
      default:
        print('Invalid choice! Please try again.');
    }
  } while (choice != '5');
}

Sample Output:

=== Calculator Menu ===

1. Add

2. Subtract

3. Multiply

4. Divide

5. Exit

Enter your choice (1-5):

You selected Addition

Goodbye!

🔹 Input Validation

Keep asking for valid input until user provides it:

import 'dart:io';

void main() {
  int age;
  String input;
  
  do {
    print('Enter your age (1-120):');
    input = stdin.readLineSync() ?? '';
    
    try {
      age = int.parse(input);
      
      if (age < 1 || age > 120) {
        print('Age must be between 1 and 120!');
        age = -1; // Invalid value to continue loop
      }
    } catch (e) {
      print('Please enter a valid number!');
      age = -1; // Invalid value to continue loop
    }
  } while (age < 1 || age > 120);
  
  print('Thank you! Your age is $age');
}

Sample Output:

Enter your age (1-120):

Please enter a valid number!

Enter your age (1-120):

Age must be between 1 and 120!

Enter your age (1-120):

Thank you! Your age is 25

🔹 Game Loop Example

Simple number guessing game using do-while:

import 'dart:io';
import 'dart:math';

void main() {
  Random random = Random();
  int secretNumber = random.nextInt(10) + 1; // 1-10
  int guess;
  int attempts = 0;
  
  print('Guess the number between 1 and 10!');
  
  do {
    print('Enter your guess:');
    String input = stdin.readLineSync() ?? '';
    
    try {
      guess = int.parse(input);
      attempts++;
      
      if (guess < secretNumber) {
        print('Too low! Try again.');
      } else if (guess > secretNumber) {
        print('Too high! Try again.');
      } else {
        print('Congratulations! You guessed it in $attempts attempts!');
      }
    } catch (e) {
      print('Please enter a valid number!');
      guess = -1; // Invalid guess to continue
    }
  } while (guess != secretNumber);
}

Sample Output:

Guess the number between 1 and 10!

Enter your guess:

Too low! Try again.

Enter your guess:

Too high! Try again.

Enter your guess:

Congratulations! You guessed it in 3 attempts!

🔹 When to Use Do...While

Choose do-while loop in these scenarios:

Perfect for:

  • Menu systems: Show menu at least once
  • Input validation: Ask for input, then validate
  • Game loops: Play at least one round
  • File processing: Process at least one record
  • User confirmation: Ask user to confirm action

Avoid when:

  • Counting loops: Use for loop instead
  • Array iteration: Use for-in loop
  • Condition might be false initially: Use while loop

🧠 Test Your Knowledge

What is the main difference between while and do-while loops?