Zig Arithmetic
Arithmetic is doing maths with numbers using operators like + and -.
Addition and subtraction give new numbers
The + operator adds. The - operator subtracts.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const a = 14;
const b = 5;
try out.print("{d}\n", .{a + b});
try out.print("{d}\n", .{a - b});
}Multiplication and division give new numbers
The * operator multiplies. The / operator divides.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const a = 7;
const b = 6;
try out.print("{d}\n", .{a * b});
try out.print("{d}\n", .{24 / 4});
}Remainder and brackets change the result
The % operator shows the leftover. Brackets run before the rest.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d}\n", .{17 % 5});
try out.print("{d}\n", .{(3 + 4) * 2});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const unit_price = 8;
const count = 3;
const fee = 2;
const paid = 30;
const subtotal = unit_price * count;
const total = subtotal + fee;
const change = paid - total;
try out.print("{d}\n", .{subtotal});
try out.print("{d}\n", .{total});
try out.print("{d}\n", .{change});
}Key points
- Addition: the + operator adds two numbers together.
- Subtraction: the - operator takes the second number away from the first.
- Multiplication: the * operator multiplies two numbers.
- Division: the / operator divides the first number by the second.
- Remainder: the % operator gives what is left over after division.
- Parentheses: round brackets group operations that must run first.
In this example, the subtotal multiplies the unit price 8 by the count 3 to get 24. The total adds the fee 2 to get 26. The change subtracts 26 from the 30 paid and prints 4.
Note
Zig does not mix an integer and a float in one operation, so both sides must share a type.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does (2 + 3) * 4 give?