# A Small Calculator

### A Small Calculator

A program can compute a value before it prints it.

```zig
const std = @import("std");

pub fn main() void {
    const x = 12;
    const y = 5;

    const sum = x + y;

    std.debug.print("{d}\n", .{sum});
}
```

The output is:

```text
17
```

The expression:

```zig
x + y
```

adds two values.

The result is stored in `sum`:

```zig
const sum = x + y;
```

Zig has the usual arithmetic operators:

| Operator | Meaning | Example |
|---|---|---|
| `+` | addition | `x + y` |
| `-` | subtraction | `x - y` |
| `*` | multiplication | `x * y` |
| `/` | division | `x / y` |
| `%` | remainder | `x % y` |

Here is a small calculator:

```zig
const std = @import("std");

pub fn main() void {
    const x = 20;
    const y = 6;

    std.debug.print("x + y = {d}\n", .{x + y});
    std.debug.print("x - y = {d}\n", .{x - y});
    std.debug.print("x * y = {d}\n", .{x * y});
    std.debug.print("x / y = {d}\n", .{x / y});
    std.debug.print("x % y = {d}\n", .{x % y});
}
```

The output is:

```text
x + y = 26
x - y = 14
x * y = 120
x / y = 3
x % y = 2
```

The division above is integer division. Both operands are integers, so the result is an integer. The fractional part is discarded.

The remainder operator gives what is left after division.

```zig
20 / 6 == 3
20 % 6 == 2
```

because:

```text
20 = 6 * 3 + 2
```

Use floating-point numbers when you want fractional results:

```zig
const std = @import("std");

pub fn main() void {
    const x: f64 = 20.0;
    const y: f64 = 6.0;

    std.debug.print("{d}\n", .{x / y});
}
```

The output is approximately:

```text
3.3333333333333335
```

A type matters. Integer arithmetic and floating-point arithmetic are different operations.

You can make the calculator clearer by naming intermediate results:

```zig
const std = @import("std");

pub fn main() void {
    const width = 80;
    const height = 25;

    const area = width * height;

    std.debug.print("area = {d}\n", .{area});
}
```

The output is:

```text
area = 2000
```

This program does not read input yet. The numbers are written directly in the source file. That is enough for a first calculator. Later we will read arguments and parse numbers.

Exercise 1-17. Change `x` and `y` and run the calculator again.

Exercise 1-18. Add a calculation for `x * x`.

Exercise 1-19. Compute the area of a rectangle.

Exercise 1-20. Change the calculator to use `f64` values.

