Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A freezer records four temperatures in degrees Celsius: , , and . A programmer uses this algorithm to find the highest.
Highest ← 0
FOR Count ← 1 TO 4
INPUT Temp
IF Temp > Highest
THEN
Highest ← Temp
ENDIF
NEXT Count
OUTPUT HighestTotalling: Total ← 0 before the loop, Total ← Total + Value inside. Counting: Count ← 0 before, Count ← Count + 1 inside (often in an IF). Maximum and minimum: start with the first value or an extreme value, and replace it with any larger (or smaller) value. Average: Total / Count after the loop.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Step 1. The given algorithm. Highest starts at . No reading is greater than , so it never changes. The output is , a temperature that was never recorded.
Step 2. The correction.
INPUT Temp
Highest ← Temp
FOR Count ← 2 TO 4
INPUT Temp
IF Temp > Highest
THEN
Highest ← Temp
ENDIF
NEXT Count
OUTPUT HighestStep 3. The new run. Highest starts at . Then is not larger; is larger, so Highest becomes ; is not larger. The output is .
Answer: (a) , because the starting value is higher than every reading; (b) the corrected algorithm outputs .
Watch out. The loop now runs from to , because the first value was input before the loop.
Log in to join the discussion.
Loading…