Nested Conditionals CS Thinking Example 1

Follow the full solution, then compare it with the other examples linked below.

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.

About Nested Conditionals

Conditional statements placed inside other conditional statements, creating multiple levels of decision-making. The inner condition is only evaluated when the outer condition is true, allowing programs to model complex, multi-step decisions.

Learn more about Nested Conditionals โ†’

More Nested Conditionals Examples