Selection CS Thinking Example 4

Follow the full solution, then compare it with the other examples linked below.

Example 4

medium
Trace 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. 1
    Step 1: Check the first condition: temp > 30 is false because 25 is not greater than 30.
  2. 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