Lesson 5 of 12

If-Else-If Chains

What if you have more than two possible outcomes? Think about letter grades: a score of 90+ is an A, 80-89 is a B, 70-79 is a C, and below 70 is an F. That's four different outcomes from one question. A single if-else can't handle that — but an if-else-if chain can.

An if-else-if chain checks multiple conditions, one after another. As soon as one condition is true, it runs that action and skips the rest. If none of the conditions are true, a final else catches everything left over.

How It Works

Think of it like a series of gates. You walk up to the first gate and it asks a question. If the answer is Yes, you go through that gate and you're done. If No, you move to the next gate and it asks a different question. This keeps going until either a gate lets you through, or you reach the final "else" at the end.

  • Check the first condition. True? Do that action. Done.
  • Not true? Check the second condition. True? Do that action. Done.
  • Still not true? Check the third condition... and so on.
  • If none of the conditions are true, the else at the end runs.

Example: Grade Calculator

A teacher enters a student's score and the program figures out the letter grade. Notice how the flowchart chains multiple diamonds together — each one checks a different condition. Step through it to see how the program moves through the chain.

Start Input score score >= 90? Yes "Grade: A" No score >= 80? Yes "Grade: B" No score >= 70? Yes "Grade: C" No "Grade: F" End
BEGIN
  INPUT score
  IF score >= 90 THEN
    OUTPUT "Grade: A"
  ELSE IF score >= 80 THEN
    OUTPUT "Grade: B"
  ELSE IF score >= 70 THEN
    OUTPUT "Grade: C"
  ELSE
    OUTPUT "Grade: F"
  END IF
END

Let's say the score is 75. Here's what happens:

  1. Is 75 >= 90? No. Move to the next check.
  2. Is 75 >= 80? No. Move to the next check.
  3. Is 75 >= 70? Yes! Output "Grade: C" and skip all remaining checks.

Important: The order of conditions matters! We check from highest to lowest. If we checked score >= 70 first, a score of 95 would get a C instead of an A, because 95 IS greater than 70 and the first matching condition wins.

The Pattern

In the flowchart, you can see the "staircase" pattern: each time the answer is No, we fall down to the next diamond. The Yes arrows all lead to their respective actions and then skip to the end. The final else (the "F" grade) catches anything that didn't match any of the conditions above it.

Key Takeaways

  • If-else-if chains let you check multiple conditions, one after another.
  • As soon as one condition is true, that action runs and all remaining checks are skipped.
  • The order of conditions matters — the first match wins.
  • A final else at the end catches everything that didn't match any condition.
  • In pseudocode: IF ... ELSE IF ... ELSE IF ... ELSE ... END IF