What are Loops?
Loops are used to execute a block of code repeatedly. They are essential for iterating over collections, performing repetitive tasks, and controlling program flow. Dart provides several types of loops to handle different iteration scenarios.
- The
for Loop
for LoopThe classic for loop repeats a block of code a specific number of times. It consists of three parts: initialization, condition, and increment/decrement.
- The
for-in Loop
for-in LoopThe for-in loop simplifies iterating over collections like lists, sets, and maps. It automatically extracts each element.
- The
while Loop
while LoopThe while loop executes a block of code as long as a given condition is true. The condition is checked before each iteration.
- The
do-while Loop
do-while LoopThe do-while loop is similar to while, but it guarantees that the code block executes at least once because the condition is checked after the iteration.
- The
forEach() Method
forEach() MethodDart collections have a forEach() method that applies a function to each element. It's a functional alternative to loops.
- Loop Control:
break and continue
break and continueUse break to exit a loop prematurely, and continue to skip the current iteration and move to the next.
- Labeled Loops
When you have nested loops, you can use labels with break or continue to specify which loop to affect.
Complete Examples
Here are more practical examples demonstrating loops in action:
Example 1: Sum of Numbers
Example 2: Iterating a Map
Example 3: Finding Prime Numbers
Key Takeaways
- Use
forloop when you know the number of iterations in advance.
- Use
- Use
for-into iterate over collections concisely.
- Use
- Use
whilewhen the number of iterations is unknown and depends on a condition.
- Use
- Use
do-whilewhen you need the loop body to execute at least once.
- Use
forEach()provides a functional way to process each element.
breakexits a loop;continueskips to the next iteration.
- Labels help control nested loops.