A program can compute a value before it prints it.
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:
17The expression:
x + yadds two values.
The result is stored in sum:
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:
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:
x + y = 26
x - y = 14
x * y = 120
x / y = 3
x % y = 2The 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.
20 / 6 == 3
20 % 6 == 2because:
20 = 6 * 3 + 2Use floating-point numbers when you want fractional results:
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:
3.3333333333333335A type matters. Integer arithmetic and floating-point arithmetic are different operations.
You can make the calculator clearer by naming intermediate results:
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:
area = 2000This 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.