4.2.1 How it works
Sharing 7 sweets between 2 people allows three different questions, and each has its operator:
| Question | Operator | 7 by 2 |
|---|---|---|
| How much does each get exactly? | / | 3.5 |
| How many whole ones does each get? | Div | 3 |
| How many are left over? | Mod | 1 |
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;
EndAlgorithmOutput
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.Divgives the integer quotient, cut towards zero.Modgives the remainder, with the sign of the dividend.- Dividing by zero stops the program.