For, While, Do-While, and For-In Loops in Dart
Loops are an essential part of Dart programming. They allow developers to execute a block of code repeatedly without writing the same code multiple times. Loops are commonly used for counting, processing collections, searching data, calculating values, and handling repeated application logic.
JustAcademy's Flutter curriculum includes Dart Programming Fundamentals, covering control statements such as if, loops, and switch, along with variables, data types, operators, functions, OOP, collections, and asynchronous programming. :contentReference[oaicite:0]{index=0}
1. What Are Loops?
A loop is a programming structure that repeatedly executes a block of code while a specified condition is satisfied or while elements remain in a collection.
For example, without a loop:
print("Hello");
print("Hello");
print("Hello");
print("Hello");
print("Hello");
Using a loop, the same task becomes:
for (int i = 1; i <= 5; i++) {
print("Hello");
}
The loop executes the print() statement five times.
2. Why Are Loops Important?
Loops help reduce repetitive code and make programs easier to maintain.
- Printing a sequence of numbers
- Processing List and Set elements
- Searching for an item
- Calculating totals and averages
- Processing user records
- Displaying product information
- Generating multiplication tables
- Performing repeated calculations
- Processing data received from APIs
- Working with application collections in Flutter
3. Types of Loops in Dart
The four important loops covered in this topic are:
- for loop
- while loop
- do-while loop
- for-in loop
4. for Loop
The for loop is useful when you know the number of iterations or when you need a counter to control the loop.
Syntax
for (initialization; condition; update) {
// code to execute
}
A typical example is:
for (int i = 1; i <= 5; i++) {
print(i);
}
Output:
1
2
3
4
5
5. Parts of a for Loop
Consider the following code:
for (int i = 1; i <= 5; i++) {
print(i);
}
| Part |
Example |
Purpose |
| Initialization |
int i = 1 |
Creates and initializes the loop variable |
| Condition |
i <= 5 |
Determines whether the loop should continue |
| Update |
i++ |
Changes the loop variable after each iteration |
| Body |
print(i) |
Contains the code executed during each iteration |
6. How a for Loop Works
The execution takes place in this order:
- Initialization executes once.
- The condition is checked.
- If the condition is true, the loop body executes.
- The update expression executes.
- The condition is checked again.
- The process continues until the condition becomes false.
7. Printing Numbers Using for
for (int i = 1; i <= 10; i++) {
print(i);
}
8. Printing Even Numbers
for (int i = 2; i <= 20; i += 2) {
print(i);
}
Output:
2
4
6
8
10
12
14
16
18
20
9. Printing Odd Numbers
for (int i = 1; i <= 20; i += 2) {
print(i);
}
10. Reverse for Loop
A for loop can also be used to count backwards.
for (int i = 10; i >= 1; i--) {
print(i);
}
Output:
10
9
8
7
6
5
4
3
2
1
11. Calculating a Sum with for
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
print("Sum = $sum");
Output:
Sum = 55
12. Multiplication Table Using for
int number = 5;
for (int i = 1; i <= 10; i++) {
print("$number x $i = ${number * i}");
}
13. while Loop
The while loop executes a block of code repeatedly as long as its condition evaluates to true.
Syntax
while (condition) {
// code
}
Example
int i = 1;
while (i <= 5) {
print(i);
i++;
}
Output:
1
2
3
4
5
14. How a while Loop Works
- Initialize a variable.
- Check the condition.
- If the condition is true, execute the loop body.
- Update the variable.
- Check the condition again.
- Continue until the condition becomes false.
15. while Loop Example with a Countdown
int count = 5;
while (count > 0) {
print(count);
count--;
}
print("Done");
16. Important Point About while Loops
A while loop may execute zero times if its condition is false before the first iteration.
int number = 10;
while (number < 5) {
print(number);
}
In this example, nothing is printed because number < 5 is false before the loop begins.
17. Avoiding Infinite while Loops
Always make sure that the values involved in the condition can eventually change so that the condition becomes false.
Incorrect:
int i = 1;
while (i <= 5) {
print(i);
}
Here, i never changes, so the condition remains true.
Correct:
int i = 1;
while (i <= 5) {
print(i);
i++;
}
18. do-while Loop
The do-while loop is similar to the while loop, but it checks the condition after executing the loop body.
Syntax
do {
// code
} while (condition);
Example
int i = 1;
do {
print(i);
i++;
} while (i <= 5);
19. Important Feature of do-while
A do-while loop executes its body at least once, even if the condition is initially false.
int number = 10;
do {
print("Number: $number");
} while (number < 5);
Output:
Number: 10
The condition is false, but the body executes once before the condition is evaluated.
20. Practical do-while Example
int option = 1;
do {
print("Showing menu...");
option++;
} while (option <= 3);
21. for-in Loop
The for-in loop is designed for iterating through the elements of an iterable collection such as a List or Set.
Syntax
for (variable in collection) {
// code
}
Example
List fruits = [
"Apple",
"Banana",
"Mango"
];
for (String fruit in fruits) {
print(fruit);
}
Output:
Apple
Banana
Mango
22. for-in with a List of Numbers
List numbers = [10, 20, 30, 40, 50];
for (int number in numbers) {
print(number);
}
23. for-in with a Set
Set cities = {
"Mumbai",
"Delhi",
"Pune",
"Bangalore"
};
for (String city in cities) {
print(city);
}
24. for-in with a Map
Maps contain key-value pairs. You can iterate through their entries using the entries property.
Map marks = {
"Rahul": 85,
"Amit": 90,
"Priya": 92
};
for (var entry in marks.entries) {
print("${entry.key}: ${entry.value}");
}
25. for Loop vs for-in Loop
| for Loop |
for-in Loop |
| Uses initialization, condition, and update |
Directly iterates through collection elements |
| Useful when an index is required |
Useful when only the value is required |
| Provides more control over the counter |
Provides simpler collection iteration |
Example: for (int i = 0; ...) |
Example: for (var item in items) |
26. Accessing List Index with a for Loop
When both the index and value are required, a traditional for loop is useful.
List fruits = [
"Apple",
"Banana",
"Mango"
];
for (int i = 0; i < fruits.length; i++) {
print("Index $i: ${fruits[i]}");
}
Output:
Index 0: Apple
Index 1: Banana
Index 2: Mango
27. break Statement
The break statement immediately terminates the loop.
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
print(i);
}
Output:
1
2
3
4
5
28. continue Statement
The continue statement skips the current iteration and moves to the next iteration.
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
print(i);
}
Output:
1
2
4
5
29. break vs continue
| Statement |
What It Does |
break |
Stops the entire loop immediately |
continue |
Skips only the current iteration |
30. Nested Loops
A loop inside another loop is called a nested loop.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
print("i = $i, j = $j");
}
}
Nested loops are useful for grids, tables, matrices, patterns, and multi-dimensional data.
31. Nested Loop Example
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 3; column++) {
print("Row: $row, Column: $column");
}
}
32. Calculating the Sum of List Values
List numbers = [10, 20, 30, 40, 50];
int total = 0;
for (int number in numbers) {
total += number;
}
print("Total = $total");
Output:
Total = 150
33. Finding the Largest Number
List numbers = [10, 45, 23, 89, 12];
int largest = numbers[0];
for (int number in numbers) {
if (number > largest) {
largest = number;
}
}
print("Largest number = $largest");
34. Finding the Smallest Number
List numbers = [10, 45, 23, 89, 12];
int smallest = numbers[0];
for (int number in numbers) {
if (number < smallest) {
smallest = number;
}
}
print("Smallest number = $smallest");
35. Searching for an Item
List products = [
"Laptop",
"Mobile",
"Tablet",
"Monitor"
];
String searchItem = "Tablet";
bool found = false;
for (String product in products) {
if (product == searchItem) {
found = true;
break;
}
}
if (found) {
print("Product found");
} else {
print("Product not found");
}
36. Counting Even Numbers
List numbers = [
10,
15,
20,
25,
30,
35
];
int count = 0;
for (int number in numbers) {
if (number % 2 == 0) {
count++;
}
}
print("Even numbers: $count");
37. Processing Student Marks
List marks = [85, 72, 90, 64, 45];
for (int mark in marks) {
if (mark >= 80) {
print("$mark - Excellent");
} else if (mark >= 60) {
print("$mark - Good");
} else if (mark >= 40) {
print("$mark - Pass");
} else {
print("$mark - Fail");
}
}
38. E-Commerce Example
List prices = [
999.0,
1499.0,
2499.0,
4999.0
];
double total = 0;
for (double price in prices) {
total += price;
}
if (total >= 5000) {
print("Free delivery");
} else {
print("Delivery charges apply");
}
39. Loops with Flutter Applications
Loops are useful when Flutter applications need to process collections of products, users, messages, categories, or other application data. JustAcademy's Flutter course covers Dart and Flutter fundamentals along with UI development, API integration, Firebase, databases, state management, testing, deployment, and practical projects. :contentReference[oaicite:1]{index=1}
Example: Product List
List products = [
"Laptop",
"Smartphone",
"Tablet",
"Smart Watch"
];
for (String product in products) {
print("Product: $product");
}
40. User Data Example
List
41. Comparison of Loop Types
| Loop |
Condition Checked |
Best Used For |
for |
Before each iteration |
Known or controlled number of iterations |
while |
Before each iteration |
Condition-based repetition |
do-while |
After each iteration |
When the body must execute at least once |
for-in |
Automatically handles collection traversal |
Iterating through collection elements |
42. for vs while
| for |
while |
| Initialization, condition, and update are together. |
Initialization and update are usually written separately. |
| Good for counter-based loops. |
Good for condition-based loops. |
| Compact syntax for counting. |
Useful when the number of iterations is not known beforehand. |
43. while vs do-while
| while |
do-while |
| Condition is checked before the body. |
Condition is checked after the body. |
| May execute zero times. |
Executes at least once. |
| Useful when execution depends on an initial condition. |
Useful when the first execution must happen before checking. |
44. Common Mistakes in Loops
Mistake 1: Creating an Infinite Loop
int i = 1;
while (i <= 5) {
print(i);
}
The value of i is never updated, so the loop condition never becomes false.
Mistake 2: Incorrect Boundary
List names = ["A", "B", "C"];
for (int i = 0; i <= names.length; i++) {
print(names[i]);
}
The correct condition is normally i < names.length because List indexes range from 0 to length - 1.
for (int i = 0; i < names.length; i++) {
print(names[i]);
}
Mistake 3: Forgetting to Update the Counter
int count = 1;
while (count <= 10) {
print(count);
// count++ is missing
}
Mistake 4: Incorrect Loop Direction
for (int i = 10; i <= 1; i--) {
print(i);
}
This condition is false initially. For a countdown, use i >= 1.
45. Best Practices for Loops
- Choose the loop that matches the problem.
- Use
for when you need a counter or index.
- Use
while when repetition depends mainly on a condition.
- Use
do-while when the code must execute at least once.
- Use
for-in for simple collection traversal.
- Make sure loop conditions can eventually become false.
- Be careful with List indexes.
- Use
break when further iteration is unnecessary.
- Use
continue when the current iteration should be skipped.
- Avoid unnecessarily complicated nested loops.
- Use meaningful loop variable names where appropriate.
46. Complete Example
void main() {
// for loop
print("For Loop:");
for (int i = 1; i <= 5; i++) {
print(i);
}
// while loop
print("While Loop:");
int count = 1;
while (count <= 5) {
print(count);
count++;
}
// do-while loop
print("Do-While Loop:");
int number = 1;
do {
print(number);
number++;
} while (number <= 5);
// for-in loop
print("For-In Loop:");
List fruits = [
"Apple",
"Banana",
"Mango"
];
for (String fruit in fruits) {
print(fruit);
}
}
47. Quick Revision
| Concept |
Meaning |
for |
Counter-based or controlled repetition |
while |
Repeats while a condition is true |
do-while |
Runs at least once before checking the condition |
for-in |
Iterates directly through collection elements |
break |
Stops the loop |
continue |
Skips the current iteration |
48. Practice Exercises
- Print numbers from 1 to 100 using a
for loop.
- Print all even numbers from 1 to 50.
- Print all odd numbers from 1 to 50.
- Print numbers from 20 to 1 in reverse order.
- Calculate the sum of numbers from 1 to 100.
- Create a multiplication table using a
for loop.
- Print numbers from 1 to 10 using a
while loop.
- Create a
do-while program that displays a menu at least once.
- Use a
for-in loop to print all values in a List.
- Find the largest value in a List.
- Find the smallest value in a List.
- Count the number of even values in a List.
- Search for a product in a List and stop using
break when it is found.
- Use
continue to skip all odd numbers.
- Create a nested loop to print a 5 × 5 pattern.
49. Key Takeaways
- Loops reduce repetitive code.
- The for loop is useful for controlled and counter-based repetition.
- The while loop checks its condition before every iteration.
- The do-while loop checks its condition after executing the body.
- The for-in loop is convenient for iterating through collection values.
- break stops a loop completely.
- continue skips the current iteration.
- Loops are frequently used when processing collections and application data in Dart and Flutter.
- Choosing the correct loop improves readability and maintainability of Dart code.
50. Learn Flutter with JustAcademy
JustAcademy's Flutter training covers Dart programming fundamentals, including variables, data types, operators, control statements such as loops and switch, functions, OOP, collections, and asynchronous programming. :contentReference[oaicite:2]{index=2}
Explore the complete Flutter course:
JustAcademy Flutter Training
Register for a course demo:
JustAcademy Course Demo Registration