Operators & Functions Grade 10

Operators perform calculations. Delphi also has a rich library of built-in functions for maths, string handling, and more.

T1Term 1 · Operators, Precedence & Functions

Arithmetic Operators

OperatorSymbolDescriptionExampleResult
Addition+Add values5 + 38
Subtraction-Subtract10 - 46
Multiplication*Multiply4 * 312
Division/Divide (returns Real)7 / 23.5
Integer DivisionDIVWhole part only (no remainder)7 DIV 23
ModulusMODRemainder only7 MOD 21

MOD and DIV Examples

CalculationWorkingMOD resultDIV result
5 MOD/DIV 25 ÷ 2 = 2 remainder 112
25 MOD/DIV 525 ÷ 5 = 5 remainder 005
17 MOD/DIV 317 ÷ 3 = 5 remainder 225
Common Uses of MOD

Even/Odd check: n MOD 2 = 0 → even
Factor check: b MOD a = 0 → a is a factor of b
Last digit: n MOD 10 → last digit of n

Worked Example — Isolating the Digits of a Number

A favourite exam task: pull a number apart digit by digit. The trick is the pair MOD 10 (gives the last digit) and DIV 10 (chops the last digit off). Repeat in a loop until nothing is left. Here we add up the digits, e.g. 1234 → 1+2+3+4 = 10.

Delphi — sum the digits
var
  iNum, iDigit, iSum : Integer;
begin
  iNum := StrToInt(edtNum.Text);   // e.g. 1234
  iSum := 0;
  while iNum > 0 do
  begin
    iDigit := iNum mod 10;   // MOD 10 grabs the LAST digit  (1234 -> 4)
    iSum   := iSum + iDigit;
    iNum   := iNum div 10;   // DIV 10 chops it off          (1234 -> 123)
  end;
  lblSum.Caption := 'Digit sum: ' + IntToStr(iSum);
end;
Same trick, many questions

The MOD 10 / DIV 10 loop is the key to counting digits, reversing a number, checking for a palindrome, or building the Luhn check digit of an ID. Swap what you do with iDigit and you have solved a whole family of questions.

Worked Example — Complete Groups and Leftovers

Whenever items must be packed into groups of a fixed size, DIV and MOD work as a pair. DIV counts how many complete groups you can fill; MOD tells you how many items are left over once those groups are full.

Imagine the tuck shop has baked 134 cupcakes for a fundraiser and each box holds 12.

QuestionCalculationAnswer
How many full boxes?134 DIV 1211 (11 × 12 = 132)
How many cupcakes are left over?134 MOD 122 (134 − 132)
Check11 * 12 + 2134 — we got every cupcake back
Delphi — boxes and leftovers
const
  BOX_SIZE = 12;
var
  iCakes, iFullBoxes, iLeftover : Integer;
begin
  iCakes     := StrToInt(edtCakes.Text);     // e.g. 134
  iFullBoxes := iCakes div BOX_SIZE;      // 11 complete boxes
  iLeftover  := iCakes mod BOX_SIZE;      // 2 cupcakes that do not fill a box
  memOut.Lines.Add('Full boxes: ' + IntToStr(iFullBoxes));
  memOut.Lines.Add('Left over:  ' + IntToStr(iLeftover));
end;

The same pair converts a total into bigger and smaller units. A movie marathon of 435 minutes is 435 DIV 60 = 7 hours and 435 MOD 60 = 15 minutes — 7 h 15 min.

What if the leftovers also need a box?

The 2 leftover cupcakes still need somewhere to go, so the shop needs 12 boxes in total, not 11. You can get this by adding one extra box whenever the leftover is more than zero, or by rounding a real division up with Ceil (see Real Division with Floor and Ceil further down). Decide first whether the question wants complete groups or all items packed.

Operator Precedence (Order of Operations)

PriorityOperators
1st (highest)Brackets ( )
2nd*   /   DIV   MOD (left to right)
3rd (lowest)+   - (left to right)
Example
result := 2 + 3 * 4;         // = 14  (3*4 first)
result := (2 + 3) * 4;       // = 20  (brackets first)
result := 10 DIV 2 + 3;      // = 8   (DIV first)

Percentages — Discounts and Percentage Change

Percentages are just divisions by 100, so they are easy to calculate once you know which value goes where. Always store the amounts in Real variables, because money and percentages seldom come out as whole numbers.

Working Out a Discount

A discount is worked out like VAT, except that you subtract it instead of adding it. A school jersey costs R450 and is on sale at 12% off:

Delphi — price after a discount
const
  DISCOUNT_RATE = 12;     // percent
var
  rPrice, rDiscount, rFinal : Real;
begin
  rPrice    := 450;
  rDiscount := rPrice * DISCOUNT_RATE / 100;   // 450 * 12 / 100 = 54
  rFinal    := rPrice - rDiscount;                // 450 - 54 = 396
  lblFinal.Caption := FloatToStrF(rFinal, ffCurrency, 8, 2);
end;

A shortcut that gives the same answer: the customer pays (100 - 12) percent of the price, so rFinal := rPrice * (100 - DISCOUNT_RATE) / 100;.

Percentage Change

How much did something go up or down, compared with where it started? Subtract the old value from the new value, divide by the old value, and multiply by 100:

percentage change = (new − old) ÷ old × 100

A positive answer means an increase; a negative answer means a decrease.

SituationOldNewWorkingChange
Taxi fare goes upR18R21(21 − 18) / 18 × 100+16.67% (increase)
Sports bag on saleR650R520(520 − 650) / 650 × 100-20% (decrease)
Delphi — percentage change
var
  rOld, rNew, rChange : Real;
begin
  rOld    := StrToFloat(edtOld.Text);       // e.g. 650
  rNew    := StrToFloat(edtNew.Text);       // e.g. 520
  rChange := (rNew - rOld) / rOld * 100;     // -20
  lblChange.Caption := FloatToStrF(rChange, ffFixed, 8, 1) + '%';
end;
Trap — divide by the OLD value

The comparison always starts from where you began, so the old value is the denominator. Dividing by the new value gives the wrong answer. Also remember the brackets around (rNew - rOld) — without them, precedence would divide first. And if the old value could be 0, check for that before dividing.

Mathematical Functions

Add Math to your uses section to access power, floor, ceil etc.

FunctionDescriptionExampleResult
sqr(x)x squared (x²)sqr(4)16
sqrt(x)Square rootsqrt(16)4.0
power(x,n)x to the power of npower(5,3)125
round(x)Round to nearest integer (an exact .5 goes to the even neighbour — see below)round(5.68)6
trunc(x)Remove decimal (truncate)trunc(5.68)5
floor(x)Round DOWNfloor(3.76)3
ceil(x)Round UPceil(3.76)4
abs(x)Absolute value (remove negative)abs(-12)12
frac(x)Fractional part onlyfrac(12.75)0.75
piValue of πpi3.14159…
random(n)Random number from 0 to n-1random(10)0–9
RoundTo(x,-n)Round to n decimal placesRoundTo(12.3456,-2)12.35

Round, Trunc, Floor and Ceil — Which One?

All four turn a real number into a whole number, but they do it differently. Floor and Ceil need the Math unit; Round and Trunc do not.

ValueRoundTruncFloorCeil
2.73223
2.52223
3.54334
-2.7-3-2-3-2
Trap — Round does not always round .5 up

The rounding you learnt in primary school (always round .5 up) is not what Round does. Delphi uses "ties go to the even number", so Round(4.5) is 4 and Round(5.5) is 6. If you need a particular direction, use Floor or Ceil instead of Round.

Real Division with Floor and Ceil — How Many Do You Need?

Many counting questions follow the same pattern: use / (real division, so the decimals are kept), then decide which way to round the answer.

Round with…Use when…Typical wording
FloorYou may not exceed a limit, so a partly affordable item does not count."How many can I afford / fit / buy?"
CeilYou must cover everything, even if the last container is only partly used."How many are needed / required?"
Delphi — Floor: how many pies can R500 buy?
var
  rBudget, rPieCost : Real;
  iPies : Integer;
begin
  rBudget  := 500;
  rPieCost := 18.50;
  iPies := Floor(rBudget / rPieCost);   // 500 / 18.50 = 27.027... -> 27
end;

27 pies cost R499.50, which fits. A 28th pie would push the total to R518, which is over budget — so the partly affordable pie is thrown away.

Delphi — Ceil: how many minibus taxis for a school trip?
var
  iLearners, iSeats, iTaxis : Integer;
begin
  iLearners := 62;
  iSeats    := 15;
  iTaxis := Ceil(iLearners / iSeats);   // 62 / 15 = 4.133... -> 5
end;

Four taxis carry only 60 learners, so a fifth is needed for the last two. Every learner must get a seat, so we round up.

Why not just use Round?

Rounding to the nearest whole number can go the wrong way: Round(4.133) is 4 taxis and two learners are left standing, and Round(27.6) would be 28 pies and an overspent budget. Pick Floor or Ceil based on the situation, not on how close the decimal is. For whole numbers that are not negative, a DIV b gives the same answer as Floor(a / b).

Inc and Dec

ProcedureEffectExampleResult
Inc(x)Increment by 1Inc(5)6
Inc(x, n)Increment by nInc(5, 3)8
Dec(x)Decrement by 1Dec(5)4
Dec(x, n)Decrement by nDec(6, 4)2

Upcase and Trim

FunctionDescriptionExampleResult
UpCase(c)Convert single char to uppercaseUpCase('a')'A'
Trim(s)Remove spaces from both endsTrim(' Hello ')'Hello'
TrimLeft(s)Remove leading spacesTrimLeft(' Hi')'Hi'
TrimRight(s)Remove trailing spacesTrimRight('Hi ')'Hi'
T3Term 3 · Ord & Chr Functions

Ord and Chr

Ord and Chr convert between characters and their ASCII numeric codes.

FunctionDescriptionExampleResult
Ord(c)Character → ASCII integerOrd('A')65
Chr(n)ASCII integer → CharacterChr(65)'A'

Caesar Cipher Example

Delphi — Shift characters by a number
var
  sInput, sOutput: string;
  i, iShift: Integer;
begin
  sInput := InputBox('Text', 'Enter text:', 'ABC');
  iShift := StrToInt(InputBox('Shift', 'Enter shift (1-25):', '3'));
  sOutput := '';
  for i := 1 to Length(sInput) do
    // wrap back to 'A' after 'Z' using MOD 26
    sOutput := sOutput + Chr(Ord('A') + (Ord(sInput[i]) - Ord('A') + iShift) mod 26);
  ShowMessage('Shifted: ' + sOutput);  // ABC → DEF, XYZ → ABC
end;
Why the MOD 26?

Without it, shifting a letter near the end of the alphabet (like 'X', 'Y' or 'Z') pushes past 'Z' into punctuation characters instead of wrapping back to 'A'. Subtracting Ord('A') first converts the letter to a 0–25 range, MOD 26 wraps it, and adding Ord('A') back converts it to a real letter again.

What is the result of 17 MOD 5?

MOD gives the remainder: 17 = 3×5 + 2, so 17 MOD 5 = 2.

What is the result of 17 DIV 5?

DIV gives the whole-number quotient: 17 DIV 5 = 3 (the .4 is discarded).

To test whether an integer n is even, you check…

An even number divides by 2 with no remainder, so n MOD 2 = 0.