Nested Conditionals CS Thinking Example 3
Follow the full solution, then compare it with the other examples linked below.
Example 3
mediumWrite 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.
Solution
- 1 Step 1: IF age >= 65 THEN discount = 50%. ELSE IF age < 12 THEN discount = 30%. ELSE: IF isStudent THEN discount = 20%. ELSE discount = 0%.
- 2 Step 2: age=20: not >= 65, not < 12, falls to ELSE. isStudent=TRUE, so discount = 20%.
Answer
20% discount. The nested structure handles age categories first, then student status within the 'general' category.
This demonstrates how nesting creates decision trees โ some conditions only apply within specific branches, like student discount only applying to non-senior, non-child customers.
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 2 mediumRewrite this nested IF as a single condition using AND: IF temperature > 20 THEN: IF NOT raining THE
Example 4 hardThe following deeply nested code is hard to read. Refactor it to be clearer: IF a > 0 THEN: IF b > 0