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}");
}
  1. 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

  1. a starts at 7.
  2. b starts at 2.
  3. a / b uses integer division, so the quotient is 3.
  4. a % b keeps the remainder, so the remainder is 1.
  5. println! prints 3 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.