free geoip
76

Dart Loops: For and While Loop Examples

Learning how to use loops is a fundamental step in mastering any programming language, including Dart. In this article, we’ll…

Learning how to use loops is a fundamental step in mastering any programming language, including Dart. In this article, we’ll explore how to use the for loop and while loop in Dart through clear, beginner-friendly examples. Loops are used to run a block of code repeatedly until a specified condition is met making your code shorter, more efficient, and easier to manage.

Dart loops examples

1. For Loop in Dart

The for loop is commonly used when the number of iterations is known ahead of time. Here’s a basic example:

void main() {
  for (int i = 1; i <= 5; i++) {
    print('Iteration $i');
  }
}

Explanation:
This loop starts with i = 1 and runs as long as i is less than or equal to 5. After each iteration, i increases by 1. The output will be:

Iteration 1  
Iteration 2  
Iteration 3  
Iteration 4  
Iteration 5

2. While Loop in Dart

The while loop is ideal when the number of iterations is not known in advance. It continues as long as a given condition is true.

void main() {
  int count = 1;
  while (count <= 5) {
    print('Count is $count');
    count++;
  }
}

Explanation:
In this example, the loop will continue to run as long as count is less than or equal to 5. With each iteration, the value of count increases by 1.

3. Practical Use Case

Let’s simulate a simple example of printing even numbers using a for loop:

void main() {
  for (int i = 2; i <= 10; i += 2) {
    print('Even number: $i');
  }
}

This loop will print all even numbers from 2 to 10.

4. Loop Control Statements

You can also use break and continue within loops to alter their flow. For example:

void main() {
  for (int i = 1; i <= 5; i++) {
    if (i == 3) {
      continue; // skip this iteration
    }
    print('Number: $i');
  }
}

This code will skip printing when i is 3.

Loops are essential in Dart for automating repetitive tasks and managing collections or input/output operations. For more about Dart loops and control flow, you can also refer to Dart’s official documentation.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *