Conditions: if-else and switch
1 Code that makes a choice
Many problems need code that behaves differently for different inputs. A cinema charges a child less than an adult. A calculator adds for + and multiplies for *.
A condition is a question about a value with a Yes or No answer, such as "is the age under 13?". The program asks it and runs one set of steps or another. The flowchart lesson drew this as a diamond. In code, it is an if statement or a switch.
Our running example is the price of a cinema ticket:
| Age | Ticket | Price |
|---|---|---|
| Under 13 | Child | 80 |
| 13 to 59 | Adult | 200 |
| 60 and over | Senior | 120 |
A first try at these rules often charges a 60-year-old or a child the adult price. Both mistakes come from the order and the edges of the checks.
2 Comparison and logic
A condition is built from comparison operators. Each one compares two values and gives true or false. Here they are for age = 13:
| Operator | Means | Example | Result |
|---|---|---|---|
== | equal to | age == 13 | true |
!= | not equal to | age != 13 | false |
< | less than | age < 13 | false |
<= | less than or equal to | age <= 13 | true |
> | greater than | age > 13 | false |
>= | greater than or equal to | age >= 13 | true |
< and <= differ only at exactly 13. Most condition bugs live at a value like that.
Comparison uses two equals signs. A single = puts a value into a variable. In JavaScript we write ===, because == converts types first and calls "13" == 13 true.
Logical operators join conditions:
| Operator | C++, Java, JavaScript, Go, Rust, C# | Python | True when |
|---|---|---|---|
| and | && | and | both sides are true |
| or | || | or | at least one side is true |
| not | ! | not | the condition is false |
So an adult is age >= 13 && age <= 59, and both parts must hold.
Both and and or stop early. When the left side of an and is false, the right side never runs. This lets a safe check guard a risky one:
if b != 0 and a % b == 0
print "b divides a"
For a = 7, b = 0, the code never calculates 7 % 0. With the sides swapped, 7 % 0 runs first and crashes with a Runtime Error. So the guard goes on the left.
3 if, else if, else
An if runs its block only when its condition is true. An else runs when it is false. For more than two paths, we put else if between them. This is an if-else chain:
if age < 13
price = 80
else if age < 60
price = 200
else
price = 120
The chain asks its questions from the top. It runs the block of the first true one and skips the rest. When none is true, the else runs. So exactly one block runs.
Here is the chain for five ages. A dash means the question is never asked:
age | age < 13? | age < 60? | price |
|---|---|---|---|
| 8 | Yes | — | 80 |
| 13 | No | Yes | 200 |
| 45 | No | Yes | 200 |
| 60 | No | No | 120 |
| 72 | No | No | 120 |
The second check needs no age >= 13. The code reaches it only when age < 13 was false.
Python writes else if as elif. In Rust, an if gives back a value, so the chain goes straight into price.
4 Order and boundaries
The chain stops at the first true check, so the order matters. Here are the first two checks swapped:
if age < 60
price = 200
else if age < 13
price = 80
else
price = 120
For age 8, age < 60 is true first, so a child pays 200. The child check never runs. When one range sits inside another, the narrow one goes first. The safe habit is to walk the number line in one direction, from the youngest up or from the oldest down.
The edges matter too. "60 and over" is age >= 60, not age > 60. With >, age 72 still gets 120, and only age 60 gets the wrong price. So for each boundary in the statement, we test the value on each side of it:
age | Why we test it | Right price |
|---|---|---|
| 0 | the smallest age | 80 |
| 12 | the last child age | 80 |
| 13 | the first adult age | 200 |
| 59 | the last adult age | 200 |
| 60 | the first senior age | 120 |
The words decide between < and <=. "Under 13" is age < 13. "60 and over" and "at least 60" are age >= 60.
5 switch: one value, many cases
Some choices compare one value with a list of exact values. Turning a day number, 1 for Monday up to 7 for Sunday, into its name is one. A chain would repeat day == seven times. A switch names the value once and lists the cases:
switch (day)names the value to compare.case 1:marks where to start when the value is 1.breakleaves the switch.default:runs when no case matches, like theelseof a chain.
Python and Rust write a switch as match, with _ as the default.
C++
A break in every case. Without it, the next case runs as well.
No strings. A switch works only on whole numbers and characters.
A break in every case. Without it, the next case runs as well.
A break in every case. Without it, the next case runs as well.
A break in every case. Without it, the code does not compile.
No break needed. Go ends each case on its own.
Every value covered. A match without the _ line is a Compile Error.
case _ is the default. Without it, a value that matches no case does nothing.
6 Fallthrough
A case label is only a starting point, and break is what stops the code there. Without break, the code runs on into the next case's lines. This is fallthrough. Here is the switch with every break missing:
switch day
case 1: name = "Monday"
case 2: name = "Tuesday"
case 3: name = "Wednesday"
case 4: name = "Thursday"
case 5: name = "Friday"
case 6: name = "Saturday"
case 7: name = "Sunday"
default: name = "Invalid"
return name
A dry run for day = 6:
| Step | Line that runs | name |
|---|---|---|
| 1 | case 6 matches | Saturday |
| 2 | falls into case 7 | Sunday |
| 3 | falls into default | Invalid |
Every day ends at default and returns "Invalid", and nothing warns us.
Fallthrough helps when several values share one answer, such as 6 and 7 for the weekend:
| Language | 6 and 7 share one case |
|---|---|
| C++, Java, JavaScript, C# | case 6: case 7: |
| Go | case 6, 7: |
| Python | case 6 | 7: |
| Rust | 6 | 7 => |
7 Mistakes to watch for
Each mistake below has an input that exposes it:
=instead of==. In C++ and JavaScript,if (day = 7)setsdayto 7 and counts as true, soday = 3gives "Sunday". The other languages refuse to run it.ifinstead ofelse if. A separateifis asked every time. For age 8,age < 13sets 80, and thenage < 60replaces it with 200.- The wide check first. With
age < 60aboveage < 13, age 8 pays the adult price. >instead of>=. For "60 and over",age > 60gives age 60 the adult price.- A missing
break. Forday = 6, the code falls intodefaultand returns "Invalid".
Bands of numbers, such as ages or marks, call for an if-else chain in order along the number line. A short list of exact values, such as days or operators, reads better as a switch.
The habit to keep: for every boundary in the statement, test the value just below it and the value on it. Most condition bugs sit at exactly those two inputs.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.