SYLLABUS 8.1.7–8.1.8 · PAPER 2 · ALSO FOR 0984 AND 2210

Library routines and maintainable programs

Library routines are ready-made functions you can use without writing them yourself. Maintainable programs are ones another programmer, or you in six months, can read and change safely.

The library routines

  • MOD(x, y): the remainder when x is divided by y.
  • DIV(x, y): how many whole times y goes into x.
  • ROUND(x, places): x rounded to that many decimal places.
  • RANDOM(): a random number from 0 to 1 inclusive.
DECLARE Eggs, Boxes, Spare : INTEGER
OUTPUT "How many eggs?"
INPUT Eggs
Boxes <- DIV(Eggs, 6)
Spare <- MOD(Eggs, 6)
OUTPUT Boxes, "full boxes and", Spare, "eggs left over"
OUTPUT "Average per box:", ROUND(Eggs / 6, 1)

Random numbers in a range

RANDOM() gives a value from 0 to 1, so it is scaled up to the range needed. For a whole number from 1 to 6, multiply by 5 to get 0 to 5, round to a whole number, then add 1: ROUND(RANDOM() * 5, 0) + 1.

Making a program maintainable

  • Meaningful identifiers: names like TotalPrice say what a value is; names like x don’t.
  • Comments: explain what a section does and why, not every line.
  • Procedures and functions: split the program into named parts that can each be tested and changed on their own.
  • Constants: put fixed values like a tax rate in one named place.

Where marks go

  • Using / instead of DIV when a whole number of boxes, teams or pages is needed.
  • Forgetting that ROUND needs the number of decimal places.
  • Scaling RANDOM() so the range is one too big or too small.
  • Describing comments as something the computer runs.
  • Naming a feature of maintainable code without saying how it helps.

Try a question

3 MARKS · MARKED ON THIS PAGE

A farm packs its eggs into boxes that each hold exactly 6 eggs. Only full boxes are sold. Write pseudocode that: - inputs the number of eggs collected today into the integer variable Eggs - uses the library routine DIV to calculate the number of full boxes, stored in Boxes - uses the library routine MOD to calculate the number of eggs left over, stored in LeftOver - outputs the message Full boxes: followed by Boxes, using OUTPUT "Full boxes: ", Boxes - then outputs the message Eggs left over: followed by LeftOver, using OUTPUT "Eggs left over: ", LeftOver You can assume Eggs is a whole number of 0 or more.

solutionPseudocode
Loading...
Type your answer first.