How do if statements work
In the last lesson we met true and false. A program uses that true or false to choose a path: this way if the condition holds, that way if it doesn't. It's the first moment a program makes a decision on its own.
True goes this way, false goes that way
Sometimes a program comes to a fork in the road.
"If so, do this; otherwise, do that."
Which path it takes depends on whether the condition is true or false.
Switch the condition between true and false below and the lit path changes.
Whether the condition is true or false decides the path.
At a fork, it takes only one side.
If true, the true side; if false, the false side.
That's "if," and it's how a program looks at the situation and picks a path.
Is the age 19 or more?
A condition usually compares something.
Say the rule is that 19 or older counts as an adult. Then the question is "Is the age 19 or more?"
If the answer is true, it's an adult; if false, not yet.
Change the age below and see how the decision splits.
Check whether the condition is true, then pick a path.
19 or older means adult; otherwise, not yet.
One value, the age, splits the decision.
That's how a condition compares values and produces true or false.
How "if" and "otherwise" fit together
"If" usually comes with a partner.
"If so, this; otherwise, that."
You write what to do when the condition is true and what to do when it's false, side by side.
This structure is what a fork looks like.
If ... then ... otherwise ....
Write down the true case and the false case in advance, and the program picks the right one each time.
It decides by itself, without us having to watch over it.
That true or false is the switch at the fork
Where have we seen this true or false before?
In the last lesson on data types, and before that in the structure section, where the ALU inside the CPU answered "Is 10 greater than 7?"
That was the switch that lights up a fork in the road.
The true or false of a comparison → the switch at the fork.
The ALU, which calculates, makes the comparison, and its true or false becomes the switch at the fork.
Pieces we learned separately connect here.
Small things came together to become a "decision."
Deciding pass or fail from a score
Let's build a small program.
"If the score is 60 or more, pass; otherwise, fail."
Enter a score and run it, and it checks whether the condition is true and picks one path: pass or fail.
Score → condition check → pass / fail.
A single score splits pass from fail.
With a condition and two branches, a program can decide for itself.
In the next lesson, we'll look at the symbols that help with calculations.