# 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.

Web page: https://pseudolearn.app/en/spec/expresiones/division

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

## 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 |

**Figure 4.2-1: Sharing seven sweets**

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.

Seven sweets between two people: three each and one left over.

### Program: Three ways of dividing

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

**Output**

```text
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.

> **Limit**
>
> - Any zero divisor stops the program with `divisionByZero`, also in `/` with reals.
> - The smallest integer divided by -1 overflows (`integerOverflow`).
> - The sign of the remainder matches that of the dividend.

> **Common mistakes**
>
> ### Program: Dividing by zero
>
> ```pseudolearn
> Algorithm EntreCero
>   Define divisor As Integer <- 0;
>   Write 10 / divisor;
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `divisionByZero` (error, 3:12): Division by zero
>
> *The program finishes with an error.*

**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.

**See also**
- [4.1 Arithmetic operators](https://pseudolearn.app/en/spec/expresiones/aritmeticos.md)
- [12.4 Mathematics and rounding](https://pseudolearn.app/en/spec/biblioteca/matematicas.md)
