Dart

8.Dart Loops

Dart Loops

Dart provides several looping constructs that allow you to iterate over a set of instructions multiple times. Here’s an overview of the common loop types in Dart with examples:

1. while Loop

The while loop executes a block of code as long as the condition is true.


void main() {
  int i = 0;

  while (i < 5) {
    print('Iteration $i');
    i++;
  }
}
  

2. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once.


void main() {
  int i = 0;

  do {
    print('Iteration $i');
    i++;
  } while (i < 5);
}
  

3. for Loop

The for loop is used to execute a block of code a specified number of times.


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

4. for-in Loop

The for-in loop is used to iterate over the elements of a collection (like a list or a set).


void main() {
  List fruits = ['Apple', 'Banana', 'Cherry'];

  for (var fruit in fruits) {
    print(fruit);
  }
}
  

5. forEach Loop

The forEach method is used to execute a function for each element in a collection.


void main() {
  List numbers = [1, 2, 3, 4, 5];

  numbers.forEach((number) {
    print('Number: $number');
  });
}
  

6. Nested Loops

You can nest loops within each other to perform more complex iterations.


void main() {
  for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
      print('i: $i, j: $j');
    }
  }
}
  

7. break and continue Statements

The break statement exits the loop immediately, and the continue statement skips to the next iteration of the loop.

Using break:


void main() {
  for (int i = 0; i < 5; i++) {
    if (i == 3) {
      break;
    }
    print('Iteration $i');
  }
}
  

Using continue:


void main() {
  for (int i = 0; i < 5; i++) {
    if (i == 3) {
      continue;
    }
    print('Iteration $i');
  }
}
  

Dart Loop Exercises

Try solving the following exercises using Dart loops:

1. Print numbers from 20 to 1 in descending order.

2. Find the squares of the first 10 numbers.

3. Find the sum of the first 10 numbers.

4. Print the multiplication table of 5.

5. Print multiplication tables from 1 to 10.

6. Create a list of 10 student names and print them.

7. Repeat each student name 3 times.

8. Skip printing a student if the name is "Anita".

9. Stop printing when the student name "Rajesh" is found.

10. Print all even numbers between 1 and 20.

Leave a Reply

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