While Loop

A while loop is like a persistent friend who keeps asking "Are we there yet?" until the answer changes! It repeatedly executes a block of code as long as a specified condition remains true.

Syntax

while (condition) {
  // Code to be executed
}

The loop continues to run as long as the condition evaluates to true. Once the condition becomes false, the loop stops.

Basic Example

Let's start with a simple countdown:

void main() {
  int count = 5;
  
  while (count > 0) {
    print('Count: $count');
    count--; // Decrease count by 1
  }
  
  print('Blast off! šŸš€');
}

Output:

Count: 5
Count: 4
Count: 3
Count: 2
Count: 1
Blast off! šŸš€

Key Components

ComponentDescriptionExample
ConditionBoolean expression that controls the loopcount > 0
Loop BodyCode that executes repeatedlyprint('Count: $count');
Update StatementModifies variables to eventually make condition falsecount--;

Common Use Cases

1. Input Validation

import 'dart:io';

void main() {
  String? input;
  
  while (input != 'yes' && input != 'no') {
    print('Please enter yes or no:');
    input = stdin.readLineSync();
  }
  
  print('Thank you for your response: $input');
}

2. Processing Collections

void main() {
  List<String> fruits = ['apple', 'banana', 'orange'];
  int index = 0;
  
  while (index < fruits.length) {
    print('Fruit ${index + 1}: ${fruits[index]}');
    index++;
  }
}

Important Tips

āš ļø Avoid Infinite Loops: Always ensure your condition will eventually become false. Otherwise, your program will run forever!

// āŒ Bad - Infinite loop
int x = 1;
while (x > 0) {
  print('This will run forever!');
  // x never changes, so x > 0 is always true
}

// āœ… Good - Loop will end
int x = 1;
while (x > 0) {
  print('Count: $x');
  x--; // x decreases and will eventually be 0
}

While vs Other Loops

  • While Loop: Use when you don't know exactly how many times to loop
  • For Loop: Use when you know the exact number of iterations
  • Do-While Loop: Use when you want to execute the code at least once before checking the condition

The while loop is perfect for situations where you need to keep doing something until a certain condition is met - like waiting for user input, processing data until it's complete, or implementing game loops!