Mathematical Operators

The most commonly used mathematical operators are: * (multiplication), / (division), DIV (integer division), MOD (remainder after integer division), + (addition) and - (subtraction).

The / operator carries out division and gives a value that, if assigned, must be assigned to a real variable. Even if both operands are integers, the result is unlikely to be an integer and cannot be assigned to an integer variable. For integer division, use the DIV and MOD operators. The DIV operator performs the division then truncates the answer so that only the whole number remains. The MOD operator gives the remainder after integer division. For example, the expression 7 DIV 3 evaluates to 2 and the expression 7 MOD 3 evaluates to 1.

An example of the use of DIV and MOD is the conversion of units such as seconds to minutes and seconds:

program DivMod;
  {$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Seconds, Minutes : integer;
begin
  write('Please enter the number of seconds. ');
  readln(Seconds);
  Minutes := Seconds DIV 60;
  Seconds := Seconds MOD 60;
  writeln('That is ', Minutes, ' minutes and ', Seconds, ' seconds.');
  readln;
end.        
      

Precedence

Within both of the following levels, the operators have equal precedence.

Higher precedence: *, /, DIV, MOD

Lower precedence: +, -

Examples

  1. The Pascal assignment v := u + a * t corresponds to the mathematical equation v = u + at. Multiplication takes precedence over addition so a bracket is not needed.
  2. The assignment Mean := (Num1 + Num2) / 2 to store the mean of two numbers needs the bracket to raise the precedence of the addition. Otherwise, the result of dividing Num2 by 2 would be added to Num1.
  3. The assignment NetPay := GrossPay – Tax – NIC - Pension to store the net pay after making three deductions from gross pay does not have brackets because the order of operation of the three subtraction operators is from left to right.
Programming - a skill for life!

Mathematical, Boolean and relational operators