Skip to content

SpecificationIV · Expressions and operators

4.2

Division, Div and Mod

There are three ways of dividing: / always gives a real, Div gives the integer quotient and Mod gives what is left over.

Markdown version

4.2.1 How it works

Sharing 7 sweets between 2 people allows three different questions, and each has its operator:

QuestionOperator7 by 2
How much does each get exactly?/3.5
How many whole ones does each get?Div3
How many are left over?Mod1
Figure 4.2-1.Seven sweets between two people: three each and one left over.

Seven circles: three for the first person, three for the second and one left over, highlighted. Below, the three operations: 7 / 2 = 3.5, 7 div 2 = 3 and 7 mod 2 = 1.

ProgramThree ways of dividing

Algorithm Dividir
  Write 7 / 2, " ", 7 Div 2, " ", 7 Mod 2;
  Write -7 Div 2, " ", -7 Mod 2;
EndAlgorithm

Output

3.5 3 1
-3 -1

The program finishes normally.

Div cuts towards zero: -7 div 2 is -3, not -4. And Mod adjusts so that this always holds: dividend = quotient × divisor + remainder. That is why -7 mod 2 is -1.

/ always returns a Real, even when both numbers are integers. Div and Mod only accept integers.

In short

  • / really divides and gives a real.
  • Div gives the integer quotient, cut towards zero.
  • Mod gives the remainder, with the sign of the dividend.
  • Dividing by zero stops the program.