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.
Asking for directions inside a big building is a nested decision: is it on this floor? If yes, is it left or right of the elevator? If no, take the stairs and ask again upstairs. You only ask 'left or right' after the first answer is yes, just as an inner if runs only after its outer test passes.
Showing a random 20 of 50 problems.
Example 1
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'.
Example 2
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.
Trace: a=3, b=7, c=2. `if a<b: if b<c: print('asc') else: if a<c: print('mid') else: print('a<b,c<a')`. Output?
Example 17
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'.
Example 18
easy
Trace: x=10. `if x>0: if x>5: print('big') else: print('small')`. Output?
Example 19
medium
Trace: a=2,b=8,c=5. `if a<b: if b<c: print('asc') else: if a<c: print('a<c<b') else: print('other')`. Output?
Example 20
easy
Rewrite `if rain: if cold: stay_in()` as one if-statement using AND.