Nested Conditionals Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Nested Conditionals.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

Conditional statements placed inside other conditional statements, creating multiple levels of decision-making.

Nested conditionals are like a decision tree โ€” first you ask one question, and depending on the answer, you ask a follow-up question.

Read the full concept explanation โ†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Nesting adds precision to decisions but increases complexity. More than 3 levels deep is usually a sign to restructure your logic.

Common stuck point: Deep nesting makes code hard to read. Consider using elif/else-if chains or combining conditions with AND/OR instead.

Worked Examples

Example 1

easy
Trace the following code when age = 15 and hasTicket = TRUE: IF age >= 12 THEN: IF hasTicket THEN: OUTPUT 'Enter'. ELSE: OUTPUT 'Buy a ticket'. ELSE: OUTPUT 'Too young'.

Solution

  1. 1
    Step 1: Check outer condition: age >= 12? 15 >= 12 is TRUE, so we enter the outer IF block.
  2. 2
    Step 2: Check inner condition: hasTicket? TRUE, so we enter the inner IF block.
  3. 3
    Step 3: OUTPUT 'Enter'. The nested IF is only reached after the outer condition passes โ€” this creates a two-level check.

Answer

Output: 'Enter'. Both conditions (age >= 12 AND hasTicket) are true.
Nested conditionals place one IF inside another, creating multi-level decision trees. The inner condition is only evaluated when the outer condition is true.

Example 2

medium
Rewrite this nested IF as a single condition using AND: IF temperature > 20 THEN: IF NOT raining THEN: OUTPUT 'Go outside'. Why might you prefer one style over the other?

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

medium
Write nested conditionals for a cinema discount: Seniors (age >= 65) get 50% off. Children (age < 12) get 30% off. Everyone else pays full price, but students with a valid ID get 20% off. Trace for age=20, isStudent=TRUE.

Example 2

hard
The following deeply nested code is hard to read. Refactor it to be clearer: IF a > 0 THEN: IF b > 0 THEN: IF c > 0 THEN: OUTPUT 'All positive'. ELSE: OUTPUT 'c not positive'. ELSE: OUTPUT 'b not positive'. ELSE: OUTPUT 'a not positive'.

Related Concepts

Background Knowledge

These ideas may be useful before you work through the harder examples.

selection