Making decisions with if
if runs a block only when its condition is true. The condition must be a real bool: Dart does not treat 0 or an empty string as false.
void main() {
int marks = 72;
if (marks >= 33) {
print('Pass');
} else {
print('Fail');
}
}
Pass
else if: more than two choices
Conditions are checked from top to bottom; the first true one wins and the rest are skipped.
void main() {
int marks = 82;
String grade;
if (marks >= 90) {
grade = 'A+';
} else if (marks >= 75) {
grade = 'A';
} else if (marks >= 60) {
grade = 'B';
} else if (marks >= 33) {
grade = 'C';
} else {
grade = 'F';
}
print('Grade: $grade');
}
Grade: A
Order matters: if marks >= 33 came first, every passing student would get a C.
switch: choosing by value
switch compares one value against several cases. In Dart 3, a case does not fall through to the next one, so break is not needed.
void main() {
int day = 3;
switch (day) {
case 1:
print('Monday');
case 2:
print('Tuesday');
case 3:
print('Wednesday');
case 6 || 7:
print('Weekend');
default:
print('Another weekday');
}
}
Wednesday
case 6 || 7: matches either value. default runs when no case matches. Dart 3 also has a switch expression that returns a value; see the Enums, Records and Pattern Matching topic.
for loops
A for loop repeats a block a counted number of times. It has three parts: start, condition, step.
void main() {
for (int i = 1; i <= 5; i++) {
print('7 x $i = ${7 * i}');
}
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
for-in: one item at a time
When you have a collection, for-in visits each item without an index:
void main() {
List<String> subjects = ['Maths', 'Science', 'English'];
for (String s in subjects) {
print(s);
}
}
Maths
Science
English
Collections also have forEach: subjects.forEach(print);. Prefer for-in in normal code; it supports break and await.
while and do-while
while checks the condition before each round, so it may run zero times. do-while checks after, so it always runs at least once.
void main() {
int balance = 1000;
int months = 0;
while (balance < 2000) {
balance += balance * 10 ~/ 100; // 10% growth, whole rupees
months++;
}
print('$months months, balance $balance');
int n = 10;
do {
print('do-while ran with n = $n');
} while (n < 5);
}
8 months, balance 2142
do-while ran with n = 10
Use while when you do not know in advance how many rounds are needed.
break and continue
breakleaves the loop immediately.continueskips the rest of this round and goes to the next.
void main() {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop after 7
print(i);
}
}
1
3
5
7
Nested loops
A loop inside a loop runs the inner loop completely for each round of the outer one. Patterns and tables use this:
void main() {
for (int row = 1; row <= 4; row++) {
String line = '';
for (int col = 1; col <= row; col++) {
line += '* ';
}
print(line);
}
}
*
* *
* * *
* * * *
To leave both loops at once, put a label on the outer loop and write break outer;.
Example: sum and average of marks
void main() {
List<int> marks = [78, 92, 65, 88, 71];
int total = 0;
int highest = marks[0];
for (int m in marks) {
total += m;
if (m > highest) highest = m;
}
print('Total: $total');
print('Average: ${(total / marks.length).toStringAsFixed(1)}');
print('Highest: $highest');
}
Total: 394
Average: 78.8
Highest: 92
Common mistakes
- Using a number as a condition:
if (count)is an error in Dart; writeif (count > 0). - Writing
if (x = 5); use==to compare. - Off-by-one loops:
i < 10runs 10 times from 0,i <= 10runs 11 times. - A
whileloop whose variable never changes runs forever. - Putting a broad condition first in an
else ifchain so the later ones never run.
Key points
if,else ifandelsechoose a path; the condition must be abool.switchcompares a value with cases; Dart 3 cases do not fall through.forcounts,for-inwalks a collection,whilerepeats while a condition holds,do-whileruns at least once.breakleaves a loop;continueskips to the next round.- Nested loops build tables and patterns.
Practice questions
1. Print all numbers from 1 to 30 that are divisible by both 3 and 5.
void main() {
for (int i = 1; i <= 30; i++) {
if (i % 3 == 0 && i % 5 == 0) print(i);
}
}
Prints 15 and 30.
2. How many times does this loop print? for (int i = 0; i < 10; i += 3) print(i);
4 times: 0, 3, 6 and 9.
3. Write a while loop that finds the sum of the digits of 4528.
void main() {
int n = 4528, sum = 0;
while (n > 0) {
sum += n % 10;
n ~/= 10;
}
print(sum); // 19
}4. What is the difference between while and do-while?
while checks the condition first and may run zero times. do-while runs the body first and checks afterwards, so it always runs at least once.
5. Use switch to print the number of days in a month number (ignore leap years).
void main() {
int month = 4;
switch (month) {
case 2:
print(28);
case 4 || 6 || 9 || 11:
print(30);
default:
print(31);
}
}
Prints 30.