Dart for loop
The for
loop in Dart is a control flow statement that allows you to execute a block of code repeatedly for a specified number of iterations. It is commonly used when you know the exact number of times you want to repeat a particular action, making it a powerful tool for iterating over ranges, collections, or performing repetitive tasks.
Syntax
The basic syntax of a for
loop in Dart is as follows:
- Initialization: This part is executed once at the beginning of the loop. It typically initializes a counter variable.
- Condition: Before each iteration, the condition is evaluated. If it evaluates to
true
, the loop body executes. If it evaluates tofalse
, the loop terminates. - Increment: This part is executed at the end of each iteration and typically updates the counter variable.
Example of a Basic for
Loop
Here’s a simple example that demonstrates a basic for
loop:
Breakdown of the Example
- Initialization:
int i = 0;
initializes the loop counteri
to 0. - Condition:
i < 5
checks ifi
is less than 5. As long as this condition is true, the loop continues to execute. - Increment:
i++
increments the value ofi
by 1 after each iteration.
Looping Through a Collection
The for
loop can also be used to iterate through collections such as lists. Here’s an example:
Nested for
Loops
You can also nest for
loops to perform multi-dimensional iterations. Here’s an example:
Output:
Enhanced for
Loop (For-Each Loop)
Dart also provides a more concise way to iterate over collections using the enhanced for
loop (also known as the for-each loop):
Syntax:
Example:
Important Notes
- Control Flow: You can use
break
to exit the loop prematurely andcontinue
to skip the current iteration and proceed to the next one. - Scope: The loop variable (e.g.,
i
) is scoped to the loop itself; it cannot be accessed outside of it.
Conclusion
The for
loop in Dart is a versatile and powerful construct for iterating over ranges, collections, or performing repetitive tasks. Understanding how to use for
loops effectively will enhance your programming skills and allow you to write efficient and clean code.