On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Arithmetic Operators
  4. 2. Comparison Operators
  5. 3. Logical Operators
  6. 4. The if Statement
  7. 5. if-else: Two Paths
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 015: if & if-else

Day6: if Statements
Lecture015 of 057
Estimated video length12 min
TargetDart 3.12
LevelBeginner

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 if statement 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

dart
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.

dart
var age = 18;
print(age == 18);   // true (equal to)
print(age != 18);   // false (not equal to)
print(age > 20);    // false
print(age >= 18);   // true
OperatorMeans
==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:

dart
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
OperatorNameTrue when…
a && bANDboth a and b are true
a || bORat least one is true
!aNOTa is false

4. The if Statement

dart
if (condition) {
  // runs only when condition is true
}
dart
var temperature = 38;
if (temperature > 35) {
  print('It is hot today.');
}
print('Done checking.');

Output

code
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:

dart
var marks = 45;
if (marks >= 50) {
  print('Pass');
} else {
  print('Fail');
}
// Fail
dart
var number = 7;
if (number % 2 == 0) {
  print('$number is even');
} else {
  print('$number is odd');
}
// 7 is odd

Code Examples

Example 1: An ATM Check

dart
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

code
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 ==

dart
if (age = 18) {
code
Error: A value of type 'int' can't be assigned to a variable of type 'bool'.

2. A condition that isn't a bool

dart
var count = 1;
if (count) {
code
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

dart
var marks = 40;
if (marks >= 50)
  print('Pass');
  print('Well done!');

Output

code
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

  1. What are 17 ~/ 5 and 17 % 5?
  2. What does 10 != 10 give?
  3. With a = true and b = false, what are a && b, a || b and !b?
  4. Write an if-else that prints Adult when age is 18 or more, and Minor otherwise.
  5. How many blocks of an if-else can run at the same time?
  6. Why does if (count) not compile when count is an int?

Practice Answers

  1. 3 and 2.
  2. false
  3. false, true, true.
dart
if (age >= 18) {
  print('Adult');
} else {
  print('Minor');
}
  1. Exactly one: either the if block or the else block.
  2. Dart only accepts a bool as a condition. Write count > 0.

Key Takeaways

  • ~/ divides to a whole number; % gives the remainder.
  • Comparisons (==, !=, <, >, <=, >=) give true or false.
  • && needs both, || needs one, ! flips.
  • if runs a block only when its condition is true; else handles the other case.
  • Always use braces, and never confuse = with ==.