Selection CS Thinking Example 4
Follow the full solution, then compare it with the other examples linked below.
Example 4
mediumTrace this code: SET temp = 25. IF temp > 30 THEN fan = 'high' ELSE IF temp > 20 THEN fan = 'low' ELSE fan = 'off'. What is the value of fan?
Solution
- 1 Step 1: Check the first condition: temp > 30 is false because 25 is not greater than 30.
- 2 Step 2: Check the next condition: temp > 20 is true, so fan is set to 'low' and no later branch runs.
Answer
'low'
Selection chooses one path from several possibilities. Once a true branch is found, that branch runs and the remaining branches are skipped.
About Selection
Choosing which block of code to execute based on whether a condition is true or false. Selection allows programs to make decisions, following one path when a condition holds and a different path otherwise, using constructs like if, else-if, and else.
Learn more about Selection โMore Selection Examples
Example 1 easy
Trace this code: SET age = 15. IF age >= 18 THEN OUTPUT 'Adult' ELSE OUTPUT 'Minor'.
Example 2 mediumWrite pseudocode using IF-ELIF-ELSE to assign a grade: 90+ = A, 80โ89 = B, 70โ79 = C, below 70 = F.
Example 3 easyWhat is the output? SET temp = 25. IF temp > 30 THEN OUTPUT 'Hot' ELIF temp > 20 THEN OUTPUT 'Warm'