---
title: "Operators and Expressions in Programming: Precedence, Div and Mod Explained: Programming Fundamentals (5)"
date: "2026-09-13"
description: "Learn arithmetic, relational and logical operators, operator precedence, integer division and modulo, and built in functions, with runnable examples."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-operators-and-expressions/"
author: "Rolando Andrade"
---

# Operators and Expressions in Programming: Precedence, Div and Mod Explained: Programming Fundamentals (5)

> Learn arithmetic, relational and logical operators, operator precedence, integer division and modulo, and built in functions, with runnable examples.

An expression is a combination of values, variables, constants, operators and functions that the computer evaluates to produce one result. An operator is the symbol or word that says what to do with the values, like `+` to add or `>` to compare. The order in which the operators run is called precedence.

After this lesson, you can write the calculations and conditions your programs need, and predict their result before you run them.

In this lesson you will:

- Use the arithmetic operators, including whole division (`Div`) and remainder (`Mod`).
- Compare values with relational operators and combine conditions with `And`, `Or` and `Not`.
- Predict the result of an expression with the rules of precedence.
- Use built in functions like `Sqrt`, `Abs`, `Round` and `Trunc`.
- Spot the operators that behave differently in StepCode and Python.

This lesson takes about 40 minutes. You only need a web browser.

## Why precedence matters

What is `1 + 2 * 3`? If you go from left to right, it is 9. If you multiply first, it is 7. A computer cannot guess, so every language fixes an order. With the usual rules of math, the answer is 7.

Most bugs in expressions are not typing mistakes. The code is valid, it runs, and it gives a wrong number because an operation ran before another one. The same happens in code written by AI agents. A formula with a missing pair of parentheses looks correct at a quick glance. To catch it, you need to read the expression the way the computer reads it.

## Arithmetic operators

Arithmetic operators work with numbers.

| Operation | StepCode | Python | Example in StepCode | Result |
|---|---|---|---|---|
| Addition | `a + b` | `a + b` | `17 + 5` | `22` |
| Subtraction | `a - b` | `a - b` | `17 - 5` | `12` |
| Multiplication | `a * b` | `a * b` | `17 * 5` | `85` |
| Division | `a / b` | `a / b` | `17 / 5` | `3.4` |
| Power | `a ^ b` | `a ** b` | `2 ^ 3` | `8` |
| Whole division | `a Div b` | `a // b` | `17 Div 5` | `3` |
| Remainder (modulo) | `a Mod b` | `a % b` | `17 Mod 5` | `2` |

Division with `/` always gives a Real, even when both numbers are Integers. `10 / 4` is `2.5`.

**Whole division** (`Div`) gives only the whole part of a division. **Modulo** (`Mod`) gives the remainder. Think of sharing 17 candies among 5 friends: each friend gets `17 Div 5`, which is 3 candies, and `17 Mod 5`, which is 2 candies, are left over. Both work only with Integers.

*Figure: Div is how many candies each friend gets. Mod is what is left when no more full rounds are possible. Move the sliders: the left over row never reaches the number of friends.*

`Mod` is more useful than it looks. A number is even when `n Mod 2` is 0. The last digit of a number is `n Mod 10`. And you can split a quantity into units, like seconds into minutes and seconds, as you will see in the practice. [Loops](/blog/programming-fundamentals-loops/#counters-and-accumulators) uses the last digit trick to add the digits of a number.

## Relational operators

Relational operators compare two values. The result is always a Boolean: `True` or `False`.

| Comparison | StepCode | Python |
|---|---|---|
| Greater than | `a > b` | `a > b` |
| Less than | `a < b` | `a < b` |
| Greater than or equal | `a >= b` | `a >= b` |
| Less than or equal | `a <= b` | `a <= b` |
| Equal | `a = b` | `a == b` |
| Not equal | `a <> b` | `a != b` |

In StepCode, you assign with the arrow (`<-`) and compare with `=`. In Python, you assign with `=` and compare with `==`. Keep this in mind every time you move between the two.

## Logical operators

Logical operators combine Booleans.

| Operation | StepCode | Python | It is True when |
|---|---|---|---|
| Negation | `Not a` | `not a` | `a` is False |
| Conjunction | `a And b` | `a and b` | both are True |
| Disjunction | `a Or b` | `a or b` | at least one is True |

A trick from the course: think of `And` as a multiplication and `Or` as an addition, with True as 1 and False as 0. If the result is 0, the answer is False. Otherwise, it is True.

- `True And False` is 1 × 0 = 0, so False.
- `True And True` is 1 × 1 = 1, so True.
- `True Or False` is 1 + 0 = 1, so True.
- `False Or False` is 0 + 0 = 0, so False.
- `True Or False And True` is 1 + 0 × 1 = 1, so True.

The trick also explains the order. Multiplication comes before addition, and `And` comes before `Or`.

## The order of precedence

When an expression has several operators, StepCode runs them in this order, from first to last:

1. Parentheses `( )`.
2. Power `^`.
3. The negative sign, as in `-x`.
4. Multiplication, division, `Div` and `Mod`: `*`, `/`, `Div`, `Mod`.
5. Addition and subtraction: `+`, `-`.
6. Comparisons: `=`, `<>`, `<`, `<=`, `>`, `>=`.
7. `Not`.
8. `And`.
9. `Or`.

Operators at the same level run from left to right. So `6 / 2 * 3` is `3 * 3`, which is 9. Power is the exception: `2 ^ 3 ^ 2` is `2 ^ 9`, which is 512, because power groups from right to left.

For the arithmetic part, the course uses the memory aid PEDMAS: Parentheses, Exponents, Divisions, Multiplications, Additions, Subtractions. Division and multiplication share one level, and so do addition and subtraction.

Pick an expression below and press **Next step** to evaluate it the way StepCode does.

*Figure: StepCode evaluates one operation at a time, following the precedence list, until a single value is left. Watch which level lights up at each step.*

When you are not sure, add parentheses. They cost nothing, and the next person who reads the code (maybe you, maybe an AI agent asked to change it) will not have to guess.

## Built in functions

Languages come with ready made functions for common tasks. These are some of the ones StepCode has:

| Function | What it does | Example | Result |
|---|---|---|---|
| `Abs(x)` | Absolute value (the number without its sign) | `Abs(-4)` | `4` |
| `Sqrt(x)` | Square root | `Sqrt(16)` | `4` |
| `Round(x)` | Rounds to the nearest whole number | `Round(2.567)` | `3` |
| `Trunc(x)` | Drops the decimals | `Trunc(2.567)` | `2` |
| `Random()` | A random Real from 0 up to (not including) 1 | `Random()` | changes |
| `PI` | The number π | `PI` | `3.141592653589793` |

StepCode also has `Sin`, `Cos`, `Tan`, `Ln` and `Exp` for math, and functions for text that you will meet in the [strings lesson](/blog/programming-fundamentals-strings/#the-tools-for-strings). In Python, `abs()` and `round()` are always available, and `sqrt`, `sin`, `cos` and `pi` come from the `math` library.

## Guided practice

Each part is a complete program. Run it with the inputs given and compare the output.

### 1. Try every arithmetic operator

**Arithmetic operators** (StepCode)

```stepcode
Program ArithmeticOperators
    Define n1, n2 As Integer;
    Write "Enter n1: ";
    Read n1;
    Write "Enter n2: ";
    Read n2;
    Write "Sum: ", n1 + n2;
    Write "Difference: ", n1 - n2;
    Write "Product: ", n1 * n2;
    Write "Division: ", n1 / n2;
    Write "Whole division: ", n1 Div n2;
    Write "Remainder: ", n1 Mod n2;
    Write "Power: ", n1 ^ n2;
EndProgram
```

Run it, type `17` and then `5`.

You should see:

```text
Enter n1: 
Enter n2: 
Sum: 22
Difference: 12
Product: 85
Division: 3.4
Whole division: 3
Remainder: 2
Power: 1419857
```

### 2. Predict the result with precedence

This is the activity from class. Before you run it, write down the value of `c`, `d` and `e` on paper.

**Precedence** (StepCode)

```stepcode
Program Precedence
    Define c As Integer;
    Define d, e As Real;
    c <- 1 + 2 * 3;
    d <- 6 / 2 * (2 + 1);
    e <- 6 / 2 / (2 + 1);
    Write "c = ", c;
    Write "d = ", d;
    Write "e = ", e;
EndProgram
```

You should see:

```text
c = 7
d = 9
e = 1
```

For `c`, the multiplication runs first: `1 + 6`. For `d`, the parentheses run first, and then `6 / 2 * 3` goes from left to right: `3 * 3`. For `e`, it is `6 / 2 / 3`, from left to right: `3 / 3`.

### 3. Combine conditions with logical operators

This continues the same class activity. `f` holds the result of a comparison, and the other variables combine it.

**Logical operators** (StepCode)

```stepcode
Program LogicalOperators
    Define f, g, h, i As Boolean;
    f <- (1 + 2) * 3 > 7;
    g <- Not f;
    h <- f Or g;
    i <- f And True;
    Write "f = ", f;
    Write "g = ", g;
    Write "h = ", h;
    Write "i = ", i;
EndProgram
```

You should see:

```text
f = True
g = False
h = True
i = True
```

`(1 + 2) * 3` is 9, and 9 is greater than 7, so `f` is True. `g` is the opposite. `h` is True because at least one side is True. `i` is True because both sides are True.

### 4. Write a real condition

A cinema gives a discount to children under 12, people 65 or older, and students under 25. The parentheses make the student rule one group.

**Discount rule** (StepCode)

```stepcode
Program DiscountTicket
    Define age As Integer;
    Define isStudent, discount As Boolean;
    Write "Enter your age: ";
    Read age;
    Write "Are you a student? (True or False): ";
    Read isStudent;
    // A discount for children, seniors, and students under 25
    discount <- age < 12 Or age >= 65 Or (isStudent And age < 25);
    Write "Discount: ", discount;
EndProgram
```

Run it with `20` and `True`. You should see:

```text
Enter your age: 
Are you a student? (True or False): 
Discount: True
```

Run it again with `30` and `True`. You should see:

```text
Enter your age: 
Are you a student? (True or False): 
Discount: False
```

Try more ages without running the program each time. Every part of the rule shows its own value.

*Figure: Or needs only one True part. The student part is a group: both isStudent and age < 25 must be True. Try age 24 and age 25 as a student.*

### 5. Split seconds with Div and Mod

A video lasts 3725 seconds. How long is that in hours, minutes and seconds? `Div` gives the whole units, and `Mod` gives what is left for the next, smaller unit.

**Seconds to hours, minutes and seconds** (StepCode)

```stepcode
Program SecondsToTime
    Define total, hours, minutes, seconds, rest As Integer;
    Write "Enter a number of seconds: ";
    Read total;
    hours <- total Div 3600;
    rest <- total Mod 3600;
    minutes <- rest Div 60;
    seconds <- rest Mod 60;
    Write total, " seconds is ", hours, " h ", minutes, " min ", seconds, " s";
EndProgram
```

Run it and type `3725`. You should see:

```text
Enter a number of seconds: 
3725 seconds is 1 h 2 min 5 s
```

In the next lesson, [Input, process and output](/blog/programming-fundamentals-sequential-structures/#build-a-program-from-a-problem), you build this same program again, one part at a time, and turn it into a clock.

### 6. Use built in functions in a formula

The quadratic formula finds the values of x where ax² + bx + c = 0. It needs a square root, so it uses `Sqrt`. Notice how the parentheses keep the whole top part over the whole bottom part.

**Quadratic formula** (StepCode)

```stepcode
Program QuadraticRoots
    Define a, b, c, root1, root2 As Real;
    Write "Enter a: ";
    Read a;
    Write "Enter b: ";
    Read b;
    Write "Enter c: ";
    Read c;
    root1 <- (-b + Sqrt(b ^ 2 - 4 * a * c)) / (2 * a);
    root2 <- (-b - Sqrt(b ^ 2 - 4 * a * c)) / (2 * a);
    Write "Root 1: ", root1;
    Write "Root 2: ", root2;
EndProgram
```

Run it with `1`, `-3` and `2`. You should see:

```text
Enter a: 
Enter b: 
Enter c: 
Root 1: 2
Root 2: 1
```

Remove the parentheses around `2 * a` and run it again. The program still runs, but `/ 2 * a` now divides by 2 and then multiplies by `a`. With `a` equal to 1 you will not notice, because dividing by 2 and multiplying by 1 gives the same answer. Now try `2`, `-6` and `4`. That equation has the same roots, 2 and 1, but the program without parentheses shows:

```text
Enter a: 
Enter b: 
Enter c: 
Root 1: 8
Root 2: 4
```

That is the kind of bug that passes a quick look and a test with easy numbers.

## Common mistakes

If you see `"==" is not part of StepCode: write "=" to compare two values.`, it means you used the Python way to compare. In StepCode, comparison uses a single `=`.

If you see `Comparisons cannot be chained: write "a < b And b < c".`, it means you wrote something like `1 < x < 10`. In math that is normal, but a computer evaluates `1 < x` first and gets a Boolean, which cannot be compared with 10. Write `1 < x And x < 10`.

If you see `"Mod" only works with Integer: convert first with "Trunc" or "Round".`, it means one side of `Mod` (or `Div`) is a Real. Whole division and remainder only make sense for whole numbers.

If you see `A Real cannot be stored where a Integer is expected: "Div" gives the whole division.`, it means you stored the result of `/` in an Integer variable. Use `Div` if you want the whole part, or make the variable `Real`.

If you see `"+" does not mix text and numbers: convert the number with "ToText".`, it means you tried something like `"Age: " + 5`. Convert the number with `ToText(5)`, or show both with `Write "Age: ", 5;`.

If you see `This divides by zero: "/" received a divisor equal to 0.` while the program runs, it means the divisor was 0. That is the [runtime error](/blog/programming-fundamentals-design-and-development-of-algorithms/#runtime-errors-stop-the-program) from the first lesson, and no language can divide by zero. Check the value before you divide. The [conditionals lesson](/blog/programming-fundamentals-conditionals/) shows how.

## Boundaries

Operators are not the same in every language, even when they look alike. Here are three real differences between StepCode and Python. Run them in StepCode:

**Negative numbers and rounding** (StepCode)

```stepcode
Program NegativeNumbers
    Write "-7 Div 2 = ", -7 Div 2;
    Write "-7 Mod 2 = ", -7 Mod 2;
    Write "Round(2.5) = ", Round(2.5);
EndProgram
```

You should see:

```text
-7 Div 2 = -3
-7 Mod 2 = -1
Round(2.5) = 3
```

Now the same in Python:

```python
print(-7 // 2, -7 % 2, round(2.5))
```

You should see:

```text
-4 1 2
```

*Figure: Above the line, StepCode cuts toward zero. Below it, Python goes down to the smaller number. For negative odd numbers they land on different answers.*

StepCode cuts the decimals toward zero, so `-7 Div 2` is -3. Python rounds down, toward the smaller number, so `-7 // 2` is -4, and the remainder changes to match. Python's `round()` also sends a value that ends in .5 to the nearest even number, so `round(2.5)` is 2. With positive numbers that do not end in .5, both languages agree, so these differences hide well. When an AI translates code from one language to another, this is exactly where a wrong result can slip in.

Also keep in mind the difference between `/` and `Div`. They are not two spellings of the same thing. `/` gives a Real with decimals, `Div` gives an Integer without them.

Finally, `=` in StepCode compares and never assigns. The arrow `<-` is the only way to store a value.

## Practice exercises

These come from the practice guide of the unit.

**Exercise 1. Evaluate by hand.** Compute each expression on paper, then check your answers by running the program.

**Expression practice** (StepCode)

```stepcode
Program ExpressionPractice
    Write "a) ", 8 + 7 * 3 + 4 * 6;
    Write "b) ", -2 ^ 3;
    Write "c) ", (33 + 3 * 4) / 5;
    Write "d) ", 2 ^ 2 * 3;
    Write "e) ", 3 + 2 * (18 - 4 ^ 2);
    Write "f) ", 16 * 6 - 3 * 2;
EndProgram
```

<details>
<summary>Solution</summary>

```text
a) 53
b) -8
c) 9
d) 12
e) 7
f) 90
```

For e), the power runs first inside the parentheses: `18 - 16` is 2, then `2 * 2` is 4, then `3 + 4` is 7.

</details>

**Exercise 2. Deduce each result.** With `a = 5`, `b = 25` and `c = 10`, what does each line show?

**Deduce the results** (StepCode)

```stepcode
Program DeduceX
    Define a, b, c As Integer;
    a <- 5;
    b <- 25;
    c <- 10;
    Write a + b + c;
    Write a + b * c;
    Write a + b / c;
    Write a + b Div c;
    Write a + b Mod c;
    Write (a + b) Div c;
    Write a + (b / c);
EndProgram
```

<details>
<summary>Solution</summary>

```text
40
255
7.5
7
10
3
7.5
```

`b Div c` is 2 and `b Mod c` is 5, and both run before the addition. In the sixth line, the parentheses make the addition run first: `30 Div 10` is 3.

</details>

**Exercise 3. Write it as an expression.** Write each formula on one line, the way a program needs it. Use `Sqrt` for the square root.

1. m divided by n, plus p.
2. m plus n divided by (p minus q).
3. (m plus n) divided by (p minus q).
4. The quadratic formula with the plus sign.

<details>
<summary>Solution</summary>

1. `m / n + p`
2. `m + n / (p - q)`
3. `(m + n) / (p - q)`
4. `(-b + Sqrt(b ^ 2 - 4 * a * c)) / (2 * a)`

</details>

**Exercise 4. Even or odd.** Write a program that reads a whole number and shows whether it is even, using `Mod`.

<details>
<summary>Solution</summary>

**Even or odd** (StepCode)

```stepcode
Program EvenOrOdd
    Define n As Integer;
    Define isEven As Boolean;
    Write "Enter a whole number: ";
    Read n;
    isEven <- n Mod 2 = 0;
    Write n, " is even: ", isEven;
EndProgram
```

With `14`, you should see:

```text
Enter a whole number: 
14 is even: True
```

With `7`, you should see:

```text
Enter a whole number: 
7 is even: False
```

</details>

## What you learned

- An expression combines values, variables, operators and functions into one result.
- `/` always gives a Real, `Div` gives the whole part and `Mod` gives the remainder.
- Relational operators give a Boolean, and `Not`, `And` and `Or` combine Booleans.
- Precedence decides the order: parentheses, power, multiplication and division, addition and subtraction, comparisons, then `Not`, `And` and `Or`.
- Operators can behave differently between languages, so check negative numbers and rounding when you translate code.

## Next steps

In the next lesson, [Input, process and output](/blog/programming-fundamentals-sequential-structures/), you will put variables and expressions together into complete programs that read data, compute and show a result.

- Review [Variables and data types](/blog/programming-fundamentals-variables-and-data-types/) if a type error in this lesson surprised you.
- Read about how a compiler checks types in [Programming languages](/blog/programming-fundamentals-programming-languages/).
