Lesson 4 of 12

If-Else Statements

In the last lesson, the if statement only did something when the answer was Yes. But what if you want to do different things depending on the answer? That's where if-else comes in.

An if-else statement gives you two paths: one thing happens when the condition is true, and a different thing happens when it's false. You always do one or the other — never both, never neither.

If vs. If-Else: What's the Difference?

  • If (last lesson): "If it's raining, grab an umbrella." — If it's NOT raining, you just skip that and do nothing extra.
  • If-Else (this lesson): "If it's raining, grab an umbrella. Otherwise, grab sunglasses." — Either way, you grab something. There's always an action on both sides.

How It Looks in a Flowchart

The diamond still asks a Yes/No question, but now both arrows lead to an action. The Yes path does one thing. The No path does a different thing. After that, both paths come back together and the flowchart continues.

Example: Can You Drive?

Imagine a simple program that checks your age and tells you whether you're old enough to drive. If you're 16 or older, it says "You can drive!" If you're younger than 16, it says "Sorry, not yet." Step through it:

Start Input your age age >= 16? Yes "You can drive!" No "Sorry, not yet" End
BEGIN
  INPUT age
  IF age >= 16 THEN
    OUTPUT "You can drive!"
  ELSE
    OUTPUT "Sorry, not yet"
  END IF
END

See how the flowchart splits into two different paths at the diamond? One path runs when the answer is Yes, and a completely different path runs when it's No. After both paths finish, they merge back together and the program ends.

Key difference from plain "if": With if-else, the No path has its own action — it doesn't just skip. The program always does exactly one of the two options.

Another Example: Even or Odd?

Here's a program that checks whether a number is even or odd. A number is even if dividing it by 2 gives no remainder (like 4, 10, 26). It's odd if there IS a remainder (like 3, 7, 15).

Start Input a number number MOD 2 = 0? Yes "It's even!" No "It's odd!" End

The MOD (modulo) operation gives you the remainder after dividing. So 10 MOD 2 = 0 (even), but 7 MOD 2 = 1 (odd). Don't worry if that's new — the important thing is the if-else pattern: one path for Yes, a different path for No, and they merge back together at the end.

Key Takeaways

  • If-else gives you two paths: one for when the condition is true, one for when it's false.
  • The program always takes exactly one of the two paths — never both, never neither.
  • In a flowchart, both the Yes and No arrows coming out of the diamond lead to their own actions.
  • After both paths finish their actions, they merge back together and the program continues.
  • In pseudocode: IF condition THEN ... ELSE ... END IF