Loops in Dart#
Loops are fundamental for performing repetitive tasks in programming. Dart provides several types of loops to handle different scenarios. Below is a comprehensive guide on each type:
For Loop in Dart#
About#
The for
loop is used to repeat a block of code a specified number of times. It is commonly used when the number of iterations is known beforehand.
How to Use#
A for
loop consists of three main parts:
- Initialization: Sets the starting value.
- Condition: Evaluates if the loop should continue.
- Increment/Decrement: Updates the loop variable.
How It Works#
- Initializes the loop variable.
- Checks the condition; if true, executes the block of code.
- Updates the loop variable.
- Repeats until the condition is false.
Example#
for (int i = 0; i < 5; i++) {
print('Iteration $i');
}
In this example, the loop prints “Iteration 0” to “Iteration 4”, running the code block 5 times.
Range-based For Loop#
About A range-based for loop is used to iterate over a range of numbers or items in a collection.
How to Use#
Utilizes a collection or range to iterate through its elements.
How It Works#
Iterates over each item in the range or collection. Executes the code block for each item.
- Example
for (int num in [1, 2, 3, 4, 5]) {
print(num);
}
This example prints each number in the list [1, 2, 3, 4, 5].
For-Each Loop in Dart#
- About
The for-each loop simplifies iterating over collections such as lists or sets.
How to Use#
Uses the for-in syntax to iterate over elements in a collection. How It Works Iterates over each element in the collection. Executes the block of code for each element.
- Example
List<String> names = ['Alice', 'Bob', 'Charlie'];
for (String name in names) {
print(name);
}
This example prints each name in the names list.
While Loop in Dart#
- About The while loop repeatedly executes a block of code as long as its condition evaluates to true.
How to Use#
Requires a condition to be checked before each iteration.
How It Works#
Checks the condition before each loop iteration. Executes the block of code if the condition is true. Repeats until the condition is false.
- Example
int count = 0;
while (count < 5) {
print('Count is $count');
count++;
}
This loop prints “Count is 0” to “Count is 4”, running until count is no longer less than 5.
- About
The do-while loop executes a block of code once before checking the condition and then continues executing as long as the condition is true.
How to Use#
- Ensures that the code block executes at least once.
How It Works#
- Executes the code block once.
- Checks the condition after the code block executes.
- Continues looping as long as the condition remains true.
Example#
int count = 0;
do {
print('Count is $count');
count++;
} while (count < 5);
This loop prints “Count is 0” to “Count is 4”, similar to the while loop, but guarantees at least one execution of the code block.