CIE IGCSE | 8.1.7 Library Routines: MOD, DIV, ROUND and RANDOM

Lesson objective

Use MOD, DIV, ROUND and RANDOM in expressions, choose suitable arguments, trace returned values and explain the limits of rounded random ranges.

Learn

8.1.7 | LIBRARY ROUTINES: MOD, DIV, ROUND AND RANDOM

01 | REUSE A ROUTINE THAT ALREADY EXISTS

Writing every useful calculation yourself would make programs longer and invite avoidable mistakes. A programming environment can provide ready-made routines for common tasks.

A library routine is a predefined routine supplied for a program to use. You need to understand its name, expected arguments and returned result, rather than write its internal definition yourself.

The routines in this lesson act as functions: each call returns a value for an expression. Cambridge uses MOD(17, 5), DIV(17, 5), ROUND(3.456, 2) and RANDOM(). Use the syllabus notation rather than assuming another language uses identical names or behaviour.

02 | READ THE CALL AS INPUTS AND A RESULT

An argument is a value or expression supplied in a call. The returned value replaces the call in the expression. For example, DIV(17, 5) returns three, so Groups receives three.

Do not use CALL before these function-style expressions. CALL is for procedures. RANDOM() has no arguments, but Cambridge specifies the empty parentheses for this library routine.

DECLARE Groups : INTEGER
Groups ← DIV(17, 5)
OUTPUT Groups

03 | DIV COUNTS COMPLETE GROUPS

Seventeen items must be placed in boxes holding five items each. Three boxes can be filled completely; two items remain. DIV returns the whole-number quotient, discarding the fractional part.

Cambridge DIV expects INTEGER arguments. Here we use non-negative amounts and a positive group size to keep the grouping meaning clear. DIV(17, 5) is three, whereas ordinary division seventeen divided by five is 3.4.

DIV is not rounding to the nearest whole number. DIV(19, 5) remains three even though 19 / 5 is 3.8. The fourth full group does not exist.

Complete groups, not nearest whole-number rounding
AmountGroup sizeOrdinary divisionDIV result
1753.43
1953.83
20544
350.60
0500

04 | MOD FINDS THE LEFTOVER

MOD returns the remainder after integer division. MOD(17, 5) returns two because three complete groups use fifteen items and two are left over.

The remainder is not the fractional part of ordinary division. For seventeen divided by five, MOD gives two, not 0.4. Cambridge MOD also expects INTEGER arguments.

For these non-negative amounts and positive group sizes, the remainder is at least zero and smaller than the group size. A remainder of zero means the amount divides exactly.

DECLARE Groups : INTEGER
DECLARE LeftOver : INTEGER
Groups ← DIV(17, 5)
LeftOver ← MOD(17, 5)
OUTPUT Groups, " complete groups; ", LeftOver, " left over"

05 | USE DIV AND MOD TOGETHER

One hundred and thirty-seven minutes contains two complete hours and seventeen remaining minutes. DIV finds the hours; MOD finds the minutes that do not form another full hour.

The two results fit back together: two times sixty plus seventeen equals one hundred and thirty-seven. For non-negative Amount and positive GroupSize, Amount = DIV(Amount, GroupSize) * GroupSize + MOD(Amount, GroupSize).

Exactly one hundred and twenty minutes gives two hours and zero remaining minutes. Less than an hour, such as forty-five minutes, gives zero complete hours and forty-five remaining minutes.

DECLARE Minutes : INTEGER
DECLARE Hours : INTEGER
DECLARE RemainingMinutes : INTEGER
Minutes ← 137
Hours ← DIV(Minutes, 60)
RemainingMinutes ← MOD(Minutes, 60)
OUTPUT Hours, " hours and ", RemainingMinutes, " minutes"

06 | REMAINDERS CAN MAKE DECISIONS

A non-negative INTEGER is even when division by two leaves no remainder. MOD(Number, 2) = 0 is therefore a BOOLEAN comparison suitable for an IF condition.

MOD itself returns an INTEGER remainder; the equality comparison produces TRUE or FALSE. Keep the routine’s result separate from the condition using it.

If every item must fit in a box, DIV alone is not always the number of boxes needed. Seventeen items with capacity five need four boxes: three full ones and another for the two leftovers. If the remainder is zero, no extra box is needed.

Boxes ← DIV(Items, Capacity)
IF MOD(Items, Capacity) <> 0
  THEN
    Boxes ← Boxes + 1
ENDIF
Assume INTEGER Items >= 0 and INTEGER Capacity > 0
ItemsCapacityFull boxesRemainderBoxes needed
175324
205404
05000

07 | CHECK A DIVISOR BEFORE USING IT

A divisor is the number you divide by. Zero is not a permitted divisor for these calculations. A box capacity of zero also has no useful grouping meaning.

For this scenario, receive valid integer inputs, then check Capacity is positive before either call. A selection guard makes the intended safe route explicit.

The guard below assumes Items is already a non-negative INTEGER. Checking Capacity alone does not validate every input.

IF Capacity > 0
  THEN
    OUTPUT DIV(Items, Capacity)
    OUTPUT MOD(Items, Capacity)
  ELSE
    OUTPUT "Capacity must be positive"
ENDIF

08 | ROUND CHANGES THE PRECISION OF A VALUE

ROUND takes a REAL value or expression and an INTEGER number of decimal places. It returns the numeric result rounded to that many decimal places.

Decimal places means positions after the decimal point. ROUND(3.456, 2) returns 3.46 because the third decimal digit is six, so the hundredths digit increases.

With zero places, rounding gives a whole-number-valued result: ROUND(3.456, 0) returns three. Do not confuse decimal places with significant figures, which count meaningful digits from a different starting point.

Examples avoid relying on an unspecified exact-half tie rule
CallReturned numeric valueReason
ROUND(3.456, 2)3.46Third decimal digit is 6
ROUND(3.451, 2)3.45Third decimal digit is 1
ROUND(3.456, 1)3.5Second decimal digit is 5 and later digits make it above the midpoint
ROUND(3.456, 0)3Value is closer to 3 than 4
ROUND(9.996, 2)10Rounding carries into the whole-number part

09 | ROUNDING IS NOT DISPLAY FORMATTING

Rounding produces a numeric value; formatting decides how to display it. ROUND(4.5, 2) has numeric value 4.5. Showing it as “4.50” requires a formatting choice, because the extra zero does not change the number.

ROUND does not change the original variable unless the result is assigned back. The first assignment below stores a rounded copy in DisplayAverage; Average remains 3.456.

Keep full working precision where useful and round the final result when required. Rounding each intermediate value can change a later total. The syllabus defines decimal-place rounding but does not state how exact halfway ties are resolved; do not assume every language’s ROUND uses the same tie rule.

DECLARE Average : REAL
DECLARE DisplayAverage : REAL
Average ← 3.456
DisplayAverage ← ROUND(Average, 2)
OUTPUT DisplayAverage

10 | TRY THE GROUPING AND ROUNDING ROUTINES

Choose INTEGER inputs for DIV and MOD, or a non-negative REAL value and decimal places for ROUND. Compare the returned values before reading the results.

The rounding demo uses nearest rounding and rounds exact positive halfway values upward. That is the demo’s stated convention, not an additional Cambridge syllabus rule. Its decimal calculation uses the entered thousandths as integers to avoid common binary floating-point display surprises.

11 | RANDOM RETURNS A VALUE FROM ZERO TO ONE

Cambridge specifies RANDOM() as returning a random number between zero and one inclusive. “Inclusive” means both endpoints belong to the stated range. It does not mean RANDOM returns only zero or one.

For example, a call might return 0.23 or 0.81. A later call may return a different value or repeat a value. You cannot predict the next exact result from the pseudocode alone.

Store a result when several instructions need the same draw. Two RANDOM() calls request two draws; they are not references to one permanently fixed random value. Real programming environments commonly generate pseudorandom values and may use different endpoint rules.

DECLARE Draw : REAL
Draw ← RANDOM()
OUTPUT Draw
OUTPUT Draw

12 | SCALE A RANDOM RANGE AND ROUND IT

Multiplying RANDOM() by six scales the stated range from zero-to-one to zero-to-six. Rounding that result to zero decimal places produces a whole-number-valued result from zero through six.

This is the example given in the Cambridge syllabus. If the draw is 0.23, multiplication gives 1.38 and ROUND gives one. If the draw is 0.81, multiplication gives 4.86 and ROUND gives five.

Do not call this a fair six-sided die: it includes zero and has seven possible values. Also, rounding a uniformly spread real draw would give the endpoints smaller intervals than the interior values, so equal probabilities do not follow from this construction.

DECLARE Draw : REAL
DECLARE Value : REAL
Draw ← RANDOM()
Value ← ROUND(Draw * 6, 0)
OUTPUT Value
Worked possible values, not a prediction of future random calls
Example DrawDraw * 6Rounded result
000
0.231.381
0.814.865
166

13 | WHY THE ENDPOINT INTERVALS ARE SHORTER

On a continuous zero-to-six scale, values below 0.5 round to zero, values between 0.5 and 1.5 round to one, and so on. Values above 5.5 round to six. Exact halfway ties depend on the rounding convention and do not affect interval widths.

The endpoint regions have width 0.5; the interior regions have width one. If the unrounded draw is uniform, an interior rounded result would therefore be about twice as likely as an endpoint. The syllabus’s range statement alone does not promise a uniform distribution.

0

0 to 0.5

Half-width region

1 to 5

Each spans width 1

Full-width regions

6

5.5 to 6

Half-width region

A fair dice simulation needs an appropriately specified random-integer method or a carefully designed mapping with endpoint handling. Do not invent a fair-dice guarantee for ROUND(RANDOM() * 6, 0).

14 | FOLLOW A RANDOM DRAW THROUGH THE FORMULA

Move the slider to choose a hypothetical returned value. This is a controlled illustration, not a real RANDOM call. It helps you see the scaling and rounding without trying to predict an unpredictable draw.

The demo uses the same stated positive-halfway-up rounding convention as above. Try draws zero, 0.23, 0.81 and one. A REAL variable can hold these whole-number-valued rounded results without implying that ROUND’s value argument should be INTEGER.

15 | PICK THE ROUTINE BY THE JOB

Need complete groups? Use DIV. Need leftovers or an exact-divisibility check? Use MOD. Need a rounded numeric result at specified decimal places? Use ROUND. Need a random draw in Cambridge’s stated zero-to-one range? Use RANDOM().

Check argument types and meanings before calling. Keep a divisor positive for these grouping scenarios, distinguish a remainder from a fraction, and distinguish numeric rounding from text formatting.

For random calculations, explain the range you can justify without claiming a predictable result or equal chances that the formula does not provide. The next lesson introduces one-dimensional arrays for storing many related values.

MATCH THE LIBRARY EXPRESSION TO ITS JOB

Terminology

Terminology

Library routine

A predefined routine provided for programs to use.

Argument

A value or expression supplied at a call.

Returned value

The result replacing a function call in an expression.

DIV

Returns the integer quotient with the fractional part discarded.

MOD

Returns the remainder from integer division.

Quotient

The result of dividing one value by another.

Remainder

The amount left after complete groups have been removed.

Divisor

The number being divided by; it must not be zero.

ROUND

Returns a REAL value or expression rounded to an INTEGER number of decimal places.

Decimal places

Positions after the decimal point.

Formatting

Controlling how a value is displayed, separately from its numeric value.

RANDOM()

Cambridge routine returning a random number from zero to one inclusive.

Inclusive range

A range whose stated endpoints are included.

Scaling

Multiplying a random draw to change its numeric range.

Random draw

One returned random value; later draws may differ or repeat.

Uniform distribution

A distribution giving equal probability to equal-width intervals in a continuous range.

Rounding interval

A region of unrounded values mapping to one rounded result.

Pseudorandom generation

Algorithmic generation of values used to behave like random draws.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which values are correct?
2. Which describe DIV and MOD here?
3. How many capacity-five boxes are needed for seventeen items?
4. Which ROUND statements are correct?
5. Which describe Cambridge RANDOM()?
6. Draw is 0.81. What are the correct intermediate and final values?
7. Which apply to ROUND(RANDOM() * 6, 0)?
8. Which are good practices?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Define a library routine and explain a benefit.

2. Calculate DIV(19, 5) and MOD(19, 5), explaining each.

3. Demonstrate converting 137 minutes to hours and remaining minutes.

4. Explain why seventeen items of capacity five need four boxes, but twenty need only four.

5. Calculate ROUND(3.456, 2) and explain why rounding is not formatting.

6. State Cambridge RANDOM()’s range and explain what two calls mean.

7. Trace ROUND(Draw * 6, 0) for Draw 0.23 and 0.81.

8. Evaluate the claim that ROUND(RANDOM() * 6, 0) is a fair six-sided die.

BUILD IT | MINIBUS PLANNING

A minibus carries eight passengers. Receive a valid non-negative INTEGER Passengers. Use DIV and MOD to calculate the number of full buses, remaining passengers and total buses needed. Test twenty-three, sixteen and zero passengers. Explain why the extra bus is conditional.

Reveal one possible solution
CONSTANT Capacity ← 8
DECLARE Passengers : INTEGER
DECLARE FullBuses : INTEGER
DECLARE Remaining : INTEGER
DECLARE BusesNeeded : INTEGER
OUTPUT "Enter passenger count"
INPUT Passengers
FullBuses ← DIV(Passengers, Capacity)
Remaining ← MOD(Passengers, Capacity)
BusesNeeded ← FullBuses
IF Remaining <> 0
  THEN
    BusesNeeded ← BusesNeeded + 1
ENDIF
OUTPUT FullBuses, " full buses; ", Remaining, " remaining passengers"
OUTPUT "Buses needed: ", BusesNeeded

Twenty-three gives two full buses, seven remaining passengers and three buses needed. Sixteen gives two full buses, no remainder and two buses needed. Zero gives zero for all three results. The capacity is a fixed positive INTEGER; this sample assumes the input count has already met the stated validity requirement.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 8.1.7 Library Routines: MOD, DIV, ROUND and RANDOM is coming soon. Complete the matching task and written questions in your exercise book.