Lesson 3 · 3 of 20
Arithmetic: div, mod and / · Pascal
Do maths in Pascal: div for whole-number division, mod for the remainder, / for decimal division, and Trunc and Round to get back to integers.

`div` divides two integers and keeps the whole part; `mod` gives the remainder. Together they turn 135 minutes into 2 h 15 min and share 17 slices of pizza among 5 friends: 3 each, with 2 left over.
`/` always gives a real number, even when both sides are integers: 17 / 5 is 3.4. That is why the result goes into share, a Double; an Integer variable could not hold it and the compiler would report an error.
As in maths, *, /, div and mod come before + and -: 2 + 3 * 4 gives 14. Brackets change the order: (2 + 3) * 4 gives 20.
To go from a real number to an integer there are two functions: `Trunc` cuts off the decimals (3.7 gives 3) and `Round` rounds (4). Watch out: when a number ends in exactly .5, Round goes to the nearest even number, so Round(2.5) is 2 and Round(3.5) is 4.
42 mod 2 = 0 is the usual way to check whether a number is even: the remainder when you divide it by 2 is zero.
Code · main.pas
program main;var minutes, slices, friends: Integer; share: Double;begin // div divides whole numbers; mod gives the remainder. minutes := 135; WriteLn(minutes, ' min = ', minutes div 60, ' h ', minutes mod 60, ' min'); slices := 17; friends := 5; WriteLn('Each friend gets ', slices div friends, ' slices'); WriteLn('Slices left over: ', slices mod friends); // / always gives a real number, even with two integers. share := slices / friends; WriteLn('Exact share: ', share:0:2); // * and / go before + and -; brackets change the order. WriteLn('2 + 3 * 4 = ', 2 + 3 * 4); WriteLn('(2 + 3) * 4 = ', (2 + 3) * 4); // From real to integer: Trunc cuts, Round rounds. WriteLn('Trunc(3.7) = ', Trunc(3.7), ' | Round(3.7) = ', Round(3.7)); // Round sends .5 to the even number. WriteLn('Round(2.5) = ', Round(2.5), ' | Round(3.5) = ', Round(3.5)); WriteLn('Even? ', 42 mod 2 = 0);end.Output · fpc main.pas && ./main
135 min = 2 h 15 min Each friend gets 3 slices Slices left over: 2 Exact share: 3.40 2 + 3 * 4 = 14 (2 + 3) * 4 = 20 Trunc(3.7) = 3 | Round(3.7) = 4 Round(2.5) = 2 | Round(3.5) = 4 Even? TRUE
Key points
divis whole-number division andmodthe remainder./always returns a real number.*and/come before+and-; brackets win.Trunccuts andRoundrounds (halves go to the even number).
Exercise
Turn 7384 seconds into hours, minutes and seconds with div and mod, and print the result as 2 h 3 min 4 s.