Procedures, Functions, Arrays and File Handling: Question 9

Syllabus 8.2

Multiple choice 1 mark

A weather monitoring system stores temperature readings, in degrees Celsius, from 3 sensors over 3 days in a two-dimensional array, Readings, declared as ARRAY[1:3, 1:3], where the first index is the sensor number and the second index is the day number. The nested loop below counts how many of the 9 readings are above 25 degrees Celsius.

DECLARE Readings : ARRAY[1:3, 1:3] OF INTEGER
DECLARE Sensor : INTEGER
DECLARE Day : INTEGER
DECLARE Count : INTEGER

Readings[1,1] ← 22
Readings[1,2] ← 27
Readings[1,3] ← 19
Readings[2,1] ← 26
Readings[2,2] ← 24
Readings[2,3] ← 30
Readings[3,1] ← 18
Readings[3,2] ← 25
Readings[3,3] ← 29

Count ← 0
FOR Sensor ← 1 TO 3
    FOR Day ← 1 TO 3
        IF Readings[Sensor, Day] > 25
            THEN
                Count ← Count + 1
        ENDIF
    NEXT Day
NEXT Sensor
OUTPUT Count

What value is output for Count?

Choose an answer to check it, then compare with the worked solution below.

Show worked solution Hide worked solution

Worked solution

Step 1: List all 9 readings and check each against the threshold

The outer loop fixes Sensor from 1 to 3; for each sensor, the inner loop checks Day from 1 to 3, testing whether Readings[Sensor, Day] > 25 (strictly greater than):

SensorDayReadings[Sensor,Day]> 25?Count after this step
1122No0
1227Yes1
1319No1
2126Yes2
2224No2
2330Yes3
3118No3
3225No (25 is not strictly greater than 25)3
3329Yes4

Step 2: Read off the final value of Count

Four readings exceed 25: 27, 26, 30 and 29. Note that Readings[3,2] = 25 does not count, since the condition uses >, not >=.

OUTPUT Count displays 4, option B.

Final answer

  • Count = 4, option B