Dart While Loop

Repeating code based on conditions

🔄 What is While Loop?

While loops repeat code as long as a condition remains true. Unlike for loops, you don't need to know the exact number of iterations beforehand. Perfect for user input validation and conditional repetition.


// Simple while loop example
void main() {
  int count = 1;
  while (count <= 5) {
    print('Count: $count');
    count++; // Important: update the condition variable
  }
}
                                    

While Loop Characteristics

Condition Check

Tests condition before each iteration

while (condition) {
  // code here
}
🔄

Variable Update

Must update condition variable inside loop

while (i < 10) {
  print(i);
  i++; // Update
}
⚠️

Infinite Loop Risk

Can run forever if condition never becomes false

// Dangerous!
while (true) {
  print('Forever');
}
🎯

Flexible Control

Great for unknown iteration counts

while (userInput != 'quit') {
  // process input
}

🔹 Basic While Loop

A simple counting example with while loop:

void main() {
  int number = 1;
  
  print('Counting from 1 to 5:');
  while (number <= 5) {
    print('Number: $number');
    number++; // Increment to avoid infinite loop
  }
  
  print('Loop finished!');
}

Output:

Counting from 1 to 5:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Loop finished!

🔹 While Loop with User Input

Keep asking for input until a specific condition is met:

import 'dart:io';

void main() {
  String password = '';
  String correctPassword = 'dart123';
  
  while (password != correctPassword) {
    print('Enter password:');
    password = stdin.readLineSync() ?? '';
    
    if (password != correctPassword) {
      print('Wrong password! Try again.');
    }
  }
  
  print('Access granted!');
}

Sample Output:

Enter password:

Wrong password! Try again.

Enter password:

Access granted!

🔹 While Loop with Lists

Process list elements using while loop:

void main() {
  List tasks = ['Study', 'Exercise', 'Cook', 'Read'];
  int index = 0;
  
  print('My daily tasks:');
  while (index < tasks.length) {
    print('${index + 1}. ${tasks[index]}');
    index++;
  }
}

Output:

My daily tasks:

1. Study

2. Exercise

3. Cook

4. Read

🔹 While Loop with Break and Continue

Control loop execution with break and continue statements:

void main() {
  int number = 0;
  
  while (number < 10) {
    number++;
    
    if (number == 5) {
      continue; // Skip printing 5
    }
    
    if (number == 8) {
      break; // Exit loop when reaching 8
    }
    
    print('Number: $number');
  }
  
  print('Loop ended at: $number');
}

Output:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 6

Number: 7

Loop ended at: 8

🔹 Common While Loop Patterns

Useful patterns for different scenarios:

🔸 Sum Until Condition

void main() {
  int sum = 0;
  int number = 1;
  
  while (sum < 50) {
    sum += number;
    print('Added $number, sum is now: $sum');
    number++;
  }
}

🔸 Menu System

void main() {
  String choice = '';
  
  while (choice != 'quit') {
    print('\nMenu: 1-Start, 2-Settings, quit-Exit');
    // choice = getUserInput(); // Simulated
    
    if (choice == '1') {
      print('Starting application...');
    } else if (choice == '2') {
      print('Opening settings...');
    }
  }
}

🔹 While vs For Loop

Choose the right loop for your situation:

Use While Loop When:

  • Unknown iterations: Don't know how many times to repeat
  • Condition-based: Continue until something happens
  • User input: Keep asking until valid input
  • File processing: Read until end of file

Use For Loop When:

  • Known iterations: Exact number of repetitions
  • Array/List processing: Go through all elements
  • Counting: Simple increment/decrement patterns

🧠 Test Your Knowledge

What happens if you forget to update the condition variable in a while loop?