Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This program works, but it is hard to maintain.
DECLARE X : INTEGER
DECLARE Y : INTEGER
DECLARE Z : INTEGER
INPUT X
Y ← 0
Z ← 0
WHILE X <> -1 DO
Y ← Y + X
Z ← Z + 1
INPUT X
ENDWHILE
OUTPUT Y / ZIt reads game scores until is typed, then outputs the average. Rewrite it so that it is easy to maintain, and correct one problem that happens when the first value typed is .
A maintainable program uses meaningful identifiers, comments, constants for values that may change, and procedures and functions for separate jobs. In the 15-mark scenario question, list every task, plan the data, write the program in commented parts, and dry-run it.
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.
A maintainable version.
// Works out the average score of a game, ended by the rogue value -1
CONSTANT EndValue ← -1
DECLARE Score : INTEGER
DECLARE TotalScore : INTEGER
DECLARE NumberOfScores : INTEGER
TotalScore ← 0
NumberOfScores ← 0
INPUT Score
WHILE Score <> EndValue DO
TotalScore ← TotalScore + Score
NumberOfScores ← NumberOfScores + 1
INPUT Score
ENDWHILE
// Only divide when at least one score was typed
IF NumberOfScores > 0
THEN
OUTPUT "Average score ", TotalScore / NumberOfScores
ELSE
OUTPUT "No scores"
ENDIFWhat changed. The identifiers say what they hold. The value is a constant with a name. Comments explain the purpose and the check. The check stops a division by zero: with only typed, the old program divided by 0.
Check. With the inputs 12, 9 and , the output is Average score 10.5. With only , it is No scores.
Log in to join the discussion.
Loading…