Nested Conditionals CS Thinking Example 2
Follow the full solution, then compare it with the other examples linked below.
Example 2
mediumRewrite 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?
Solution
- 1 Step 1: The nested version checks temperature > 20 first, then checks NOT raining.
- 2 Step 2: Combined: IF temperature > 20 AND NOT raining THEN: OUTPUT 'Go outside'. This produces identical behaviour.
- 3 Step 3: The combined version is shorter but the nested version is clearer when the conditions have different 'else' actions. Use nesting when each level has its own ELSE branch.
Answer
IF temperature > 20 AND NOT raining THEN OUTPUT 'Go outside'. Use nesting when each condition has separate ELSE branches.
Nested conditionals and compound boolean expressions can often achieve the same result. Choosing between them depends on readability and whether each condition requires separate handling.
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 1 easy
Trace the following code when age = 15 and hasTicket = TRUE: IF age >= 12 THEN: IF hasTicket THEN: O
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