Nested Conditionals CS Thinking Example 1
Follow the full solution, then compare it with the other examples linked below.
Example 1
easyTrace 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 Step 1: Check outer condition: age >= 12? 15 >= 12 is TRUE, so we enter the outer IF block.
- 2 Step 2: Check inner condition: hasTicket? TRUE, so we enter the inner IF block.
- 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
Example 2 medium
Rewrite this nested IF as a single condition using AND: IF temperature > 20 THEN: IF NOT raining THE
Example 3 mediumWrite nested conditionals for a cinema discount: Seniors (age >= 65) get 50% off. Children (age < 12
Example 4 hardThe following deeply nested code is hard to read. Refactor it to be clearer: IF a > 0 THEN: IF b > 0