Dart – 6 – Loops (for, while, do-while)

Loops in Dart Programming

Loops are essential constructs in Dart that enable developers to perform repetitive tasks and iterate over data efficiently. Dart provides three primary types of loops: forwhile, and do-while. Each of these loops serves a specific purpose, offering flexibility and control over how code is executed.

The For Loop

The for loop in Dart is designed for iterating over a range of values or elements. It consists of three parts: initialization, condition, and update, separated by semicolons.


for (initialization; condition; update) {
    // Statements to be executed repeatedly
}
    

Here’s an example of a for loop in Dart that prints numbers from 1 to 5:


for (int i = 1; i <= 5; i++) {
    print(i);
}
    

In this example, the loop initializes i to 1, checks if i is less than or equal to 5, and increments i by 1 in each iteration.

The While Loop

The while loop repeatedly executes a block of statements as long as a specified condition is true.


while (condition) {
    // Statements to be executed as long as the condition is true
}
    

Here’s an example of a while loop that counts down from 3 to 0:


int count = 3;

while (count >= 0) {
    print(count);
    count--;
}
    

The loop continues to execute while the count is greater than or equal to 0.

The Do-While Loop

The do-while loop is similar to the while loop but ensures that the loop block is executed at least once before checking the condition.


do {
    // Statements to be executed at least once
} while (condition);
    

Here’s an example of a do-while loop that generates random numbers until one greater than 50 is produced:


import 'dart:math';

int randomNumber;

do {
    randomNumber = Random().nextInt(100); // Generate a random number between 0 and 99
    print('Random Number: $randomNumber');
} while (randomNumber <= 50);
    

In this example, the loop block is executed at least once to generate a random number, and the condition is checked afterward.

Control Flow in Loops

Loops in Dart support control flow statements like break and continue.

  • Break: The break statement is used to exit a loop prematurely when a certain condition is met. For example, to exit a for loop when a specific value is found.
  • Continue: The continue statement is used to skip the current iteration and proceed to the next iteration of the loop. For example, to skip even numbers in a loop.
Conclusion

Loops are powerful constructs in Dart that allow you to automate repetitive tasks, efficiently process data, and control the flow of your program. Whether you use a forwhile, or do-while loop, you can make your code more dynamic and responsive. Mastering the use of loops and control flow statements is essential for writing efficient and reliable Dart code.