Basics
Arithmetic
Integers and Division
Integer arithmetic in Rust truncates division and exposes the remainder with %.
Program
Play the program to compute an integer quotient and remainder.
arithmetic.rs
Replay: real traced execution (multi-file project)
fn main() {
let a = 7;
let b = 2;
let quotient = a / b;
let remainder = a % b;
println!("{quotient} {remainder}");
}
a ← 7, b ← 2, quotient ← 3, remainder ← 1
1fn main() {2 let → 7a = 7;3 let → 2b = 2;4 let quotien→ 3t = 7a / 2b;5 let remainde→ 1r = 7a % 2b;6 println!("{quotient} {remainder}");7}output3 1
Follow the Math
astarts at7.bstarts at2.a / buses integer division, so the quotient is3.a % bkeeps the remainder, so the remainder is1.println!prints3 1. | calculation | result | | --- | --- | |7 / 2| 3 | |7 % 2| 1 | | printed output | 3 1 |
integer division
`7 / 2` truncates toward zero, giving `3`.
modulo
`7 % 2` is the remainder `1`.
immutable bindings
`a` and `b` are read-only after binding.
Exercise: arithmetic.rs
Reproduce the output 3 1, then change b and predict the quotient and remainder before running it.