Mastering While Loops in Dart

Lesson Overview

Welcome to the thrilling realm of iterations and loops. In this lesson, let's dive into Dart's while and do while loops! While loops play a vital role in programming due to their ability to execute code blocks repeatedly until a specific condition becomes false. They operate similarly to performing an action until a condition changes — such as washing a car until it's completely clean. A while loop operates until the condition becomes false. Conversely, a do while loop will execute the code block at least once, regardless of the condition.

The Syntax of While Loops

A while loop in Dart consists of a condition and a code block. The code block is executed if the given condition is true.

while (condition) { // Loop continues while the condition is true
    // Block of code
}

What are While Loops?

while loops in Dart are control flow statements that enable a specific code block to execute repeatedly while a certain condition holds true. For example, imagine a scenario where you continue reading a book while the light is on. Here's what a while loop in Dart might look like:

int counter = 0; // Initialize with 0
while (counter < 5) { // Loop while counter is less than 5
    print(counter); // Print the counter
    counter++; // Increment the counter by 1 after each loop iteration
}
/*
Prints:
0
1
2
3
4
*/

Introducing Do While Loops

The do while loop in Dart is similar to the while loop, but with one crucial difference: the code block within the do while loop will execute at least once, even if the condition is not met. Here's the general syntax for a do while loop in Dart:

do {
    // Code block to be executed
} while (condition);

And here's a simple practical example:

int counter = 5;
do {
    print(counter);
    counter++;
} while (counter < 5);
/*
Prints:
5
*/

In this example, despite the counter being initialized at 5 which does not satisfy the condition counter < 5, the code block is still executed once. Hence, 5 is printed out.

Practical Examples with While Loops

Suppose you need to execute a countdown from the number 5 to 0. You can quickly achieve this using a while loop as follows:

int number = 5; // Initialize with 5

while (number >= 0) { // While number is at least 0
    print('Number is: $number'); // Print the number
    number--; // Decrease the number by one after each iteration
}
/*
Prints:
Number is: 5
Number is: 4
Number is: 3
Number is: 2
Number is: 1
Number is: 0
*/
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal