Looping is an essential concept in programming that allows us to repeat a certain block of code multiple times. It helps in automating repetitive tasks and simplifying complex operations. In Dart, a versatile programming language developed by Google, looping is achieved through different loop control statements and constructs. This article explores everything you need to know about looping in Dart, including loop control statements like break and continue. We also provide concise and detailed examples of practical programs that demonstrate these concepts.
The for Loop
The for loop is one of the most commonly used looping constructs in Dart. It allows you to iterate over a sequence of values or perform a certain number of iterations. The basic syntax of a for loop is as follows:
for (initialization; condition; update) {
// Code to be executed in each iteration
}
Here’s a practical example that prints the numbers from 1 to 10 using a for loop:
void main() {
for (var i = 1; i <= 10; i++) {
print(i);
}
}
We initialize the loop counter i to 1, specify the condition i <= 5 to determine when the loop should continue, and increment i by 1 after each iteration using the i++ statement.
The while Loop
The while loop is another looping construct in Dart that repeatedly executes a block of code as long as a specified condition is true. The general syntax of a while loop is as follows:
while (condition) {
// Code to be executed in each iteration
}
Let’s consider a practical example that prints the even numbers between 1 and 10 using a while loop:
void main() {
var i = 1;
while (i <= 10) {
if (i % 2 == 0) {
print(i);
}
i++;
}
}
We initialize the loop counter i to 1 and check if it is less than or equal to 10. If i is an even number, we print it to the console. Finally, we increment i by 1 using i++ to move to the next iteration.
The do-while Loop
The do-while loop is similar to the while loop, but it ensures that the code block is executed at least once before the condition is evaluated. The general syntax of a do-while loop is as follows:
do {
// Code to be executed in each iteration
} while (condition);
Let’s see an example that allows the user to exit the program by entering ‘q’ using the do-while loop:
import 'dart:io';
void main() {
var exitKey;
// Run the loop until the user enters 'q'
do {
// Prompt the user to enter 'q' to exit the program
print("Enter 'q' to exit the program: ");
// Read the user input and convert it to lowercase for case-insensitive comparison
exitKey = stdin.readLineSync()?.toLowerCase();
} while (exitKey != "q"); // Continue looping as long as the user input is not 'q'
// The loop exits when the user enters 'q', so print the exit message
print("Exiting Program...");
}
The program prompts the user to enter ‘q’ to exit the program. It uses the do-while loop to repeatedly ask for user input until the input is equal to ‘q’. The stdin.readLineSync()?.toLowerCase() function reads the user input and converts it to lowercase using the toLowerCase() method, ensuring that the comparison with ‘q’ is case-insensitive.
After the loop exits, the program prints the exit message, indicating that the program is ending.
The for-in Loop
The for-in loop in Dart allows you to iterate over elements in a collection, such as lists or sets, without the need for an explicit index. It simplifies the process of iterating through collections and accessing each element. The general syntax of a for-in loop is as follows:
for (var element in iterable) {
// Code to be executed for each element
}
Here’s an example that demonstrates iterating through a collection using the for-in loop:
void main() {
List<String> languages = ['C', 'Dart', 'JavaScript', "Python", "Swift"];
for (var language in languages) {
print(language);
}
}
We have a list of strings called languages that contains five elements. The for-in loop iterates over each element in the languages list and assigns it to the variable language. The loop then executes the code block within its body, which prints the value of language to the console.
The for-in loop is particularly useful when working with collections or iterable objects. It abstracts away the details of accessing elements by index and provides a more readable and concise way to iterate through the elements.
You can use the for-in loop with various types of collections, including lists, sets, and even user-defined classes that implement the iterable interface. It offers a flexible and convenient approach to iterating over elements in Dart.
Loop Control Statements: break and continue
Dart provides two loop control statements, break and continue, that allow you to alter the flow of a loop.
The break statement is used to exit a loop prematurely. When encountered, it immediately terminates the loop and transfers control to the next statement following the loop. Let’s consider an example that finds the first number divisible by both 2 and 3 between 1 and 10 using a for loop with a break statement:
void main() {
for (var i = 1; i <= 10; i++) {
if (i % 2 == 0 && i % 3 == 0) {
print('Number: $i');
break;
}
}
}
The loop iterates through numbers from 1 to 10. When it encounters the first number that is divisible by both 2 and 3 (i.e., 6), it prints the number and immediately exits the loop using the break statement.
The continue statement is used to skip the remaining code in a loop iteration and move to the next iteration. It allows you to selectively execute the code based on certain conditions. Here’s an example that prints the odd numbers between 1 and 10 using a for loop with a continue statement:
void main() {
for (var i = 1; i <= 10; i++) {
if (i % 2 == 0) {
// If even number, move to next iteration
continue;
}
print(i);
}
}
The loop iterates through numbers from 1 to 10. If the number is even, it skips the remaining code in that iteration using the continue statement. Consequently, only the odd numbers are printed to the console.
Conclusion
Looping is a fundamental concept in programming, and Dart provides several loop constructs to cater to different looping requirements. This post explored the for, while, do-while, and for-in loops and learned how to use loop control statements like break and continue to alter the flow of a loop. We also provided practical program examples that demonstrated these concepts in action. By mastering these looping techniques, you’ll be able to solve complex problems efficiently and write more concise and powerful code in Dart.
Sources
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!