Skip to main content

Overview

Do-while loops are similar to while loops, but with one key difference: the condition is checked after the loop body executes. This guarantees that the loop body runs at least once, even if the condition is initially false.

Basic Syntax

do {
  // Code to execute
} while (condition);
The loop body executes first, then the condition is checked. If the condition is true, the loop repeats.

Basic Do-While Loop

Here’s a simple do-while loop with increments:
print('\nCiclo Do While Incremento');
int numero = 1;

do {
  print('Número: $numero');
  numero += 2;
} while (numero <= 5);
// Output: Número: 1
//         Número: 3
//         Número: 5

Custom Increment Values

You can use different increment values:
print('\nCiclo Do While Incremento');
int numero = 0;

do {
  print('Número: $numero');
  numero += 2;
} while (numero <= 5);
// Output: Número: 0
//         Número: 2
//         Número: 4

Complete Example

void main() {
  // Do-While with increment
  print('\nCiclo Do While Incremento');
  int numero = 1;
  
  do {
    print('Número: $numero');
    numero += 2;
  } while (numero <= 5);

  // Do-While with different increments
  print('\nCiclo Do While Incremento');
  numero = 0;
  
  do {
    print('Número: $numero');
    numero += 2;
  } while (numero <= 5);
}

Do-While vs While

1

While Loop

Checks the condition before executing the body. May never execute if condition is false initially.
2

Do-While Loop

Checks the condition after executing the body. Always executes at least once.

Key Difference Example

// While loop - may not execute
int x = 10;
while (x < 5) {
  print('This will not print');
}

// Do-while loop - always executes once
int y = 10;
do {
  print('This will print once');
} while (y < 5);
Use do-while loops when you need to ensure the code runs at least once, such as displaying a menu or prompting for input.

When to Use Do-While Loops

Ideal Use Cases:

  • User input validation (prompt at least once)
  • Menu-driven programs (show menu at least once)
  • Game loops (execute game logic before checking exit condition)
  • Retry operations (attempt at least once before checking success)

Example: Input Validation

int userInput;
do {
  print('Enter a number between 1 and 10:');
  // userInput = getUserInput();
} while (userInput < 1 || userInput > 10);

Common Patterns

Execute then check

do {
  // Code that must run at least once
} while (condition);

Counting with do-while

int i = 0;
do {
  print(i);
  i++;
} while (i < n);

Custom increments

int i = 0;
do {
  print(i);
  i += step;
} while (i < limit);

Loop Control Statements

You can use break and continue with do-while loops:
int count = 0;
do {
  count++;
  
  if (count == 3) {
    continue; // Skip 3
  }
  
  if (count > 5) {
    break; // Exit at 6
  }
  
  print(count);
} while (count < 10);
// Output: 1, 2, 4, 5
Be careful with do-while loops! Since they always execute at least once, make sure the first execution is safe even when the condition is false.

Best Practices

  • Use do-while when you need guaranteed first execution
  • Initialize variables before the loop
  • Ensure the condition will eventually become false to avoid infinite loops
  • Consider readability - if the “at least once” behavior isn’t obvious, add a comment
  • Use while loops if you’re not sure the loop should execute at all

Comparison Table

FeatureWhile LoopDo-While Loop
Condition CheckBefore executionAfter execution
Minimum Executions01
Use WhenMay not need to executeMust execute at least once
Syntax ClarityMore commonLess common but specific

Practical Example

Here’s a practical menu example:
void main() {
  String choice;
  
  do {
    print('\n=== Menu ===');
    print('1. Option 1');
    print('2. Option 2');
    print('3. Exit');
    print('Enter your choice:');
    
    // choice = readUserInput();
    choice = '3'; // Simulated input
    
    if (choice == '1') {
      print('You selected Option 1');
    } else if (choice == '2') {
      print('You selected Option 2');
    }
  } while (choice != '3');
  
  print('Goodbye!');
}

Build docs developers (and LLMs) love