Unlock the full potential of Dart programming by mastering control flow structures and loops. In this comprehensive guide, explore the intricacies of for, while, and do-while loops, and learn how to effectively use break and continue statements. Gain a solid understanding of these fundamental concepts, paving the way for more efficient and structured Dart programming.
Dart, a programming language developed by Google, provides various control flow structures for implementing loops. The most common types of loops in Dart are for, while, and do-while. Here’s an overview of each:
dart
for (initialization; condition; iteration) {
// code to be executed
}
dart
for (int i = 0; i < 5; i++) { print('Iteration $i'); }
The while loop in dart continues to execute a block of code as long as the specified condition is true.
dart
while (condition) {
// code to be executed
}
dart
int count = 0; while (count < 3) { print('Count is $count'); count++; }
The do-while loop in Dart is similar to the while loop, but it guarantees that the block of code is executed at least once before the condition is checked.
dart
do {
// code to be executed
} while (condition);
dart
int num = 1; do { print('Number is $num'); num++; } while (num <= 3);
These are the basic loop constructs in Dart. You can use them to create iterative structures in your code, and they play a crucial role in controlling the flow of your program. Additionally, Dart provides other features like break and continue statements for more fine-grained control within loops.
Let’s walk through a complete example of a for loop in Dart, including an explanation of each part.
dart
void main() { // Example 1: Simple for loop print("Example 1: Simple for loop"); for (int i = 0; i < 5; i++) { print("Iteration $i"); } // Example 2: Looping through a list print("\nExample 2: Looping through a list"); List<String> fruits = ["Apple", "Banana", "Orange", "Grapes"]; for (int i = 0; i < fruits.length; i++) { print("Fruit at index $i: ${fruits[i]}"); } // Example 3: Using a for loop to calculate a sum print("\nExample 3: Using a for loop to calculate a sum"); int sum = 0; for (int i = 1; i <= 5; i++) { sum += i; } print("Sum of numbers from 1 to 5 is $sum"); }
for (int i = 0; i < 5; i++): This is the basic structure of a for loop.
int i = 0: Initialization – Setting up the loop variable i to start at 0.
i < 5: Condition – The loop will continue as long as i is less than 5.
i++: Iteration – Incrementing i by 1 after each iteration.
print(“Iteration $i”): Printing the value of i during each iteration.
List<String> fruits = [“Apple”, “Banana”, “Orange”, “Grapes”]: Declaring a list of strings.
for (int i = 0; i < fruits.length; i++): Looping through the list using its length.
print(“Fruit at index $i: ${fruits[i]}”): Printing each element of the list along with its index.
int sum = 0;: Initializing a variable sum to zero.
for (int i = 1; i <= 5; i++): Looping from 1 to 5 (inclusive) to calculate the sum.
sum += i;: Accumulating the sum by adding the current value of i in each iteration.
print(“Sum of numbers from 1 to 5 is $sum”): Printing the final sum.
This example demonstrates the versatility of the for loop in Dart, showcasing its usage in simple counting, iterating through lists, and performing a cumulative calculation.
Let’s go through a complete example of a while loop in Dart, including an explanation of each part.
dart
void main() { // Example 1: Simple while loop print("Example 1: Simple while loop"); int count = 0; while (count < 5) { print("Count is $count"); count++; } // Example 2: Using while loop to find the power of 2 print("\nExample 2: Using while loop to find the power of 2"); int base = 2; int exponent = 1; int result = 1; while (exponent <= 5) { result *= base; exponent++; } print("2 raised to the power of 5 is $result"); // Example 3: Using while loop with input print("\nExample 3: Using while loop with input"); int Number = 0; print("Enter a positive number (enter -1 to stop): "); while (Number != -1) { Number = int.parse(stdin.readLineSync()!); print("You entered: $Number"); } print("Loop terminated as -1 was entered."); }
int count = 0;: Initializing a variable count to 0.
while (count < 5): The loop will continue as long as count is less than 5.
print(“Count is $count”): Printing the value of count during each iteration.
count++;: Incrementing count by 1 after each iteration.
int base = 2;, int exponent = 1;, int result = 1;: Initializing variables for the power calculation.
while (exponent <= 5): Looping until the exponent reaches 5.
result *= base;: Calculating the power of 2 in each iteration.
exponent++;: Incrementing the exponent after each iteration.
print(“2 raised to the power of 5 is $result”): Printing the final result.
int Number = 0;: Initializing a variable for input.
print(“Enter a positive number (enter -1 to stop): “): Prompting the for input.
while (Number != -1): The loop continues until the enters -1.
Number = int.parse(stdin.readLineSync()!);: Reading input from the console.
print(“You entered: $Number”): Printing the entered number during each iteration.
The loop terminates when the enters -1.
These examples illustrate how the while loop in Dart can be used for simple counting, iterative calculations, and interactive input scenarios.
Let’s walk through a complete example of a do-while loop in Dart, including an explanation of each part.
dart
import 'dart:io'; void main() { // Example 1: Simple do-while loop print("Example 1: Simple do-while loop"); int num = 1; do { print("Number is $num"); num++; } while (num <= 3); // Example 2: Using do-while loop for input validation print("\nExample 2: Using do-while loop for input validation"); int Input; do { print("Enter a number between 1 and 10: "); Input = int.parse(stdin.readLineSync()!); } while (Input < 1 || Input > 10); print("You entered a valid number: $Input"); // Example 3: Performing an action at least once print("\nExample 3: Performing an action at least once"); String Choice; do { print("Do you want to continue? (yes/no): "); Choice = stdin.readLineSync()!; } while (Choice.toLowerCase() == 'yes'); print("You chose to stop."); }
int num = 1;: Initializing a variable num to 1.
do { … } while (num <= 3);: The loop body will be executed at least once, and then it will continue as long as num is less than or equal to 3.
print(“Number is $num”);: Printing the value of num during each iteration.
num++;: Incrementing num by 1 after each iteration.
int Input;: Declaring a variable to store input.
do { … } while (Input < 1 || Input > 10);: The loop continues until the enters a number between 1 and 10 (inclusive).
print(“You entered a valid number: $Input”);: Printing the valid input.
String Choice;: Declaring a variable to store choice.
do { … } while (Choice.toLowerCase() == ‘yes’);: The loop continues as long as the enters “yes” (case-insensitive).
print(“You chose to stop.”);: Printing a message when the decides to stop.
These examples demonstrate the use of the do-while loop in Dart, which ensures that the loop body is executed at least once before checking the loop condition. This can be useful for scenarios where you want to perform an action and then decide whether to continue based on a condition.
The break statement in Dart is used to prematurely exit a loop.
Let’s go through a complete example of using break in a for loop:
dart
void main() { // Example: Using break in a for loop print("Example: Using break in a for loop"); for (int i = 0; i < 5; i++) { print("Iteration $i"); if (i == 2) { print("Breaking out of the loop at iteration 2"); break; // Exit the loop when i is equal to 2 } } print("Loop finished"); }
for (int i = 0; i < 5; i++): This is a simple for loop that iterates from 0 to 4.
print(“Iteration $i”): Printing the current iteration number during each loop iteration.
if (i == 2) { … }: Checking if the current iteration is equal to 2.
print(“Breaking out of the loop at iteration 2”): Printing a message when the condition is met.
break;: This statement is executed when i is equal to 2, causing the loop to exit prematurely.
print(“Loop finished”): Printing a message indicating that the loop has finished.
When you run this program, you’ll see output similar to:
Example: Using break in a for loop
Iteration 0
Iteration 1
Iteration 2
Breaking out of the loop at iteration 2
Loop finished
The break statement is particularly useful when you want to exit a loop based on a specific condition. In this example, the loop breaks when the iteration variable i is equal to 2.
The output shows that the loop finishes prematurely after encountering the break statement.
The continue statement in Dart is used to skip the rest of the current iteration of a loop and proceed to the next one.
Let’s go through a complete example of using continue in a for loop:
dart
void main() { // Example: Using continue in a for loop print("Example: Using continue in a for loop"); for (int i = 0; i < 5; i++) { if (i == 2) { print("Skipping iteration 2 using continue"); continue; // Skip the rest of the loop body and move to the next iteration } print("Iteration $i"); } print("Loop finished"); }
for (int i = 0; i < 5; i++): This is a simple for loop that iterates from 0 to 4.
if (i == 2) { … }: Checking if the current iteration is equal to 2.
print(“Skipping iteration 2 using continue”): Printing a message when the condition is met.
continue;: This statement is executed when i is equal to 2, causing the loop to skip the rest of the loop body and move to the next iteration.
print(“Iteration $i”): This line is skipped for the iteration where i is equal to 2.
print(“Loop finished”): Printing a message indicating that the loop has finished.
Example: Using continue in a for loop
Iteration 0
Iteration 1
Skipping iteration 2 using continue
Iteration 3
Iteration 4
Loop finished
As you can see, when the loop encounters the continue statement during iteration 2, it skips the print statement and moves on to the next iteration.
The output shows that iteration 2 is skipped, and the loop continues with the remaining iterations.
let’s create a quiz based on the concepts we covered about Dart control flow, loops, for, while, do-while loops, break, and continue.
Each question will be followed by an explanation of the correct answer.
a) To declare variables
b) To define functions
c) To create a loop that repeats a statement or a block of statements
Explanation: The correct answer is (c). The for loop is used to create a loop that repeats a statement or a block of statements a specified number of times.
a) Before the loop body is executed
b) After the loop body is executed
c) Only once at the beginning of the loop
Explanation: The correct answer is (a). In a while loop, the condition is checked before the loop body is executed.
a) Before the loop body is executed
b) After the loop body is executed
c) Only once at the beginning of the loop
Explanation: The correct answer is (b). In a do-while loop, the condition is checked after the loop body is executed, ensuring that the loop body is executed at least once.
a) Continues to the next iteration of the loop
b) Exits the loop prematurely
c) Skips the current iteration and moves to the next one
Explanation: The correct answer is (b). The break statement in Dart is used to prematurely exit a loop.
a) To exit the loop
b) To skip the rest of the current iteration and move to the next one
c) To restart the loop from the beginning
Explanation: The correct answer is (b). The continue statement is used to skip the rest of the current iteration and move to the next one.
a) Before the loop body is executed
b) After the loop body is executed
c) Only once at the beginning of the loop
Explanation: The correct answer is (c). In a for loop, the loop variable is initialized only once at the beginning of the loop.
a) To initialize the loop variable
b) To determine when to exit the loop
c) To calculate the sum of loop iterations
Explanation: The correct answer is (b). The loop condition in a while loop determines when to exit the loop.
a) Before the loop body is executed
b) After the loop body is executed
c) Only once at the beginning of the loop
Explanation: The correct answer is (a). In a do-while loop, the loop condition is checked before the loop body is executed.
dart
for (int i = 0; i < 3; i++) {
print(“Iteration $i”);
}
a) Prints “Iteration 0” three times
b) Prints “Iteration 0,” “Iteration 1,” “Iteration 2”
c) Prints “Iteration 1” three times
Explanation: The correct answer is (b). The for loop iterates three times, printing “Iteration 0,” “Iteration 1,” and “Iteration 2.”
a) Before the loop body is executed
b) After the loop body is executed
c) During each iteration with the iteration statement
Explanation: The correct answer is (c). In a for loop, the loop variable is updated during each iteration with the iteration statement.
dart
int count = 0;
while (count < 4) {
print(“Count is $count”);
count++;
}
a) Count is 0, 1, 2, 3, 4
b) Count is 0, 1, 2, 3
c) Count is 1, 2, 3, 4
Explanation: The correct answer is (b). The while loop prints “Count is 0,” “Count is 1,” “Count is 2,” and “Count is 3.”
a) Zero times
b) One time
c) Infinite times
Explanation: The correct answer is (b). In a do-while loop, the loop body is executed at least once, even if the condition is initially false.
dart
do {
print(“This is a do-while loop”);
} while (false);
a) Prints the message once
b) Prints the message twice
c) Does not print anything
Explanation: The correct answer is (a). The do-while loop prints the message once even though the condition is false initially.
a) To exit the loop
b) To skip the rest of the current iteration and move to the next one
c) To restart the loop from the beginning
Explanation: The correct answer is (b). The continue statement is useful for skipping the rest of the current iteration and moving to the next one.
a) To initialize the loop variable
b) To determine when to exit the loop
c) To calculate the sum of loop iterations
Explanation: The correct answer is (b). The loop condition in a for loop determines when to exit the loop.
I just like the valuable info you supply for your articles. I will bookmark your blog and check again here frequently. I am fairly sure I?ll learn many new stuff right here! Good luck for the next!
Hey there would you mind stating which blog platform you’re working with? I’m planning to start my own blog soon but I’m having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your layout seems different then most blogs and I’m looking for something completely unique. P.S Sorry for being off-topic but I had to ask!
Howdy! Someone in my Facebook group shared this website with us so I came to look it over. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and great design and style.