Intro To Loops In Dart – Control Flow Dart Programming Guide

Haris Bin Nasir Avatar

·

·

Loops are a fundamental concept in programming that allow you to repeat a block of code multiple times. Dart provides several types of loops, including for, for-in, while, and do-while loops. Each loop serves a different purpose and can be used to iterate over collections, repeat actions until a condition is met, or execute code a specific number of times. In this post, we will cover all these loop types with explanations and examples.

For further information on detailed topics of Dart, click here.

1. For Loop

The for loop is one of the most commonly used loops in Dart. It allows you to execute a block of code a specific number of times, usually by iterating over a range of values.

Syntax:
for (initialization; condition; increment/decrement) {
  // Code to execute
}
Example 1: Basic For Loop
void printNumbers() {
  for (int i = 1; i <= 5; i++) {
    print(i);
  }
}

void main() {
  printNumbers();  // Output: 1 2 3 4 5
}

In this example, the for loop starts from 1 and increments i until it reaches 5. The loop prints each number during each iteration.

Example 2: For Loop with Decrement
void printCountdown() {
  for (int i = 5; i > 0; i--) {
    print(i);
  }
}

void main() {
  printCountdown();  // Output: 5 4 3 2 1
}

This example demonstrates a countdown using a for loop that decrements the value of i from 5 to 1.

2. For-In Loop

The for-in loop is used to iterate over elements in a collection, such as a List, Set, or Map. It provides a simpler and more readable way to loop through collections without manually managing the loop index.

Example 1: Iterate Over a List
void printFruits() {
  List<String> fruits = ['Apple', 'Banana', 'Cherry'];
  for (String fruit in fruits) {
    print(fruit);
  }
}

void main() {
  printFruits();  // Output: Apple Banana Cherry
}

In this example, the for-in loop iterates over each element in the fruits list and prints it.

Example 2: Iterate Over a Set
void printUniqueNumbers() {
  Set<int> numbers = {1, 2, 3, 4, 5};
  for (int number in numbers) {
    print(number);
  }
}

void main() {
  printUniqueNumbers();  // Output: 1 2 3 4 5
}

Here, the for-in loop is used to iterate over a Set of unique numbers and print each element.

3. While Loop

The while loop repeatedly executes a block of code as long as a specified condition is true. It’s useful when you don’t know in advance how many times the loop will run, but you have a condition that needs to be checked.

Syntax:
while (condition) {
  // Code to execute
}
Example 1: Basic While Loop
void printNumbers() {
  int i = 1;
  while (i <= 5) {
    print(i);
    i++;
  }
}

void main() {
  printNumbers();  // Output: 1 2 3 4 5
}

In this example, the while loop starts with i = 1 and continues to print i as long as i is less than or equal to 5.

Example 2: Sum of Numbers Using While Loop
void calculateSum(int limit) {
  int sum = 0;
  int i = 1;

  while (i <= limit) {
    sum += i;
    i++;
  }

  print('The sum of numbers from 1 to $limit is $sum');
}

void main() {
  calculateSum(5);  // Output: The sum of numbers from 1 to 5 is 15
}

In this example, the while loop iterates from 1 to the given limit (in this case, 5) and calculates the sum of all numbers in that range. The loop continues until i exceeds the limit, and the final sum is printed.

4. Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will be executed at least once. This is because the condition is checked after the loop has executed.

Syntax:
do {
  // Code to execute
} while (condition);
Example 1: Basic Do-While Loop
void printNumbers() {
  int i = 1;
  do {
    print(i);
    i++;
  } while (i <= 5);
}

void main() {
  printNumbers();  // Output: 1 2 3 4 5
}

In this example, the do-while loop prints numbers from 1 to 5. Even if the condition is initially false, the loop will run at least once.

Example 2: Product of Numbers Using Do-While Loop
void calculateProduct(int limit) {
  int product = 1;
  int i = 1;

  do {
    product *= i;
    i++;
  } while (i <= limit);

  print('The product of numbers from 1 to $limit is $product');
}

void main() {
  calculateProduct(5);  // Output: The product of numbers from 1 to 5 is 120
}

In this example, the do-while loop calculates the product of all numbers from 1 to the given limit (in this case, 5). The loop ensures that the multiplication occurs at least once, even if the limit is very small. The final product is printed after the loop completes.

Conclusion

Dart loops are powerful constructs that allow you to repeat actions efficiently. Whether you are iterating over a collection, executing code a set number of times, or checking conditions, loops make it easy to manage repetitive tasks. By mastering for, for-in, while, and do-while loops, you can write more efficient and effective Dart code.

Happy Coding…!!!

Leave a Reply

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