On this page12 sections
Lecture 015: if & if-else
| Day | 6: if Statements |
| Lecture | 015 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
So far, every line of every program has run, top to bottom. Real programs make decisions: show "Pass" or "Fail", allow the withdrawal or decline it. This lecture covers the operators that ask questions, and the
ifstatement that acts on the answer.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 006–007: variables and data types, especially bool.
Learning Objectives
- Use the arithmetic operators, including
~/and% - Compare values with
==,!=,<,>,<=,>= - Combine conditions with
&&,||and! - Run code only when a condition is true, with
if - Choose between two paths with
if-else
1. Arithmetic Operators
print(7 + 2); // 9
print(7 - 2); // 5
print(7 * 2); // 14
print(7 / 2); // 3.5 (always gives a double)
print(7 ~/ 2); // 3 (whole-number division)
print(7 % 2); // 1 (the remainder)% is handy for "is it even?": a number is even when number % 2 == 0.
2. Comparison Operators
A comparison asks a yes/no question. The answer is a bool: true or false.
var age = 18;
print(age == 18); // true (equal to)
print(age != 18); // false (not equal to)
print(age > 20); // false
print(age >= 18); // true| Operator | Means |
|---|---|
== | equal to |
!= | not equal to |
> / < | greater than / less than |
>= / <= | greater than or equal / less than or equal |
= gives a value (age = 18); == asks whether two values are equal (age == 18).
3. Logical Operators
Combine several questions into one:
var hasTicket = true;
print(age >= 18 && hasTicket); // true: both must be true
print(age < 12 || age > 60); // false: at least one must be true
print(!hasTicket); // false: flips true and false| Operator | Name | True when… |
|---|---|---|
a && b | AND | both a and b are true |
a || b | OR | at least one is true |
!a | NOT | a is false |
4. The if Statement
if (condition) {
// runs only when condition is true
}var temperature = 38;
if (temperature > 35) {
print('It is hot today.');
}
print('Done checking.');Output
It is hot today.
Done checking.With temperature = 20, only Done checking. would print. The line after the if always runs.
5. if-else: Two Paths
else runs when the condition is false. Exactly one of the two blocks runs, never both:
var marks = 45;
if (marks >= 50) {
print('Pass');
} else {
print('Fail');
}
// Failvar number = 7;
if (number % 2 == 0) {
print('$number is even');
} else {
print('$number is odd');
}
// 7 is oddCode Examples
Example 1: An ATM Check
void main() {
var balance = 5000;
var withdraw = 7000;
var pinCorrect = true;
if (!pinCorrect) {
print('Wrong PIN.');
}
if (pinCorrect && withdraw <= balance) {
balance = balance - withdraw;
print('Please take your cash: Rs $withdraw');
} else {
print('Transaction declined.');
}
print('Balance: Rs $balance');
var isWeekend = false;
var isHoliday = true;
if (isWeekend || isHoliday) {
print('The bank is closed today.');
} else {
print('The bank is open.');
}
}Output
Transaction declined.
Balance: Rs 5000
The bank is closed today.The PIN was right, but withdraw <= balance was false, so && made the whole condition false.
Change withdraw to 2000 and the cash is paid out.
Common Beginner Mistakes
1. = instead of ==
if (age = 18) {Error: A value of type 'int' can't be assigned to a variable of type 'bool'.2. A condition that isn't a bool
var count = 1;
if (count) {Error: A value of type 'int' can't be assigned to a variable of type 'bool'.Some languages treat 1 as true. Dart doesn't: write if (count > 0).
3. Leaving out the braces
var marks = 40;
if (marks >= 50)
print('Pass');
print('Well done!');Output
Well done!Without { }, only the first line belongs to the if. The indentation fooled us: Well done! always runs. Always use braces.
4. Putting ; after the condition: if (marks >= 50); { ... } ends the if at the ;, so
the block always runs.
Practice Questions
- What are
17 ~/ 5and17 % 5? - What does
10 != 10give? - With
a = trueandb = false, what area && b,a || band!b? - Write an
if-elsethat printsAdultwhenageis 18 or more, andMinorotherwise. - How many blocks of an
if-elsecan run at the same time? - Why does
if (count)not compile whencountis anint?
Practice Answers
3and2.falsefalse,true,true.
if (age >= 18) {
print('Adult');
} else {
print('Minor');
}- Exactly one: either the
ifblock or theelseblock. - Dart only accepts a
boolas a condition. Writecount > 0.
Key Takeaways
~/divides to a whole number;%gives the remainder.- Comparisons (
==,!=,<,>,<=,>=) givetrueorfalse. &&needs both,||needs one,!flips.ifruns a block only when its condition is true;elsehandles the other case.- Always use braces, and never confuse
=with==.