Trip odometer
A delivery van's odometer shows a reading in kilometres at the start of the day. The driver then makes three trips. Read the starting reading and the length of each trip, and after every trip print the new odometer reading on its own line. The reading must accumulate: the second line shows the start plus the first two trips, and the third line the start plus all three.
Input
Four lines, each a non-negative integer: the starting reading, then the distance of trip one, trip two and trip three.
Output
Three lines: the odometer reading after trip one, after trip two and after trip three.
Example 1
Input
12000 35 0 120
Output
12035 12035 12155
12000 + 35 = 12035; the second trip is 0 km so the reading stays 12035; then 12035 + 120 = 12155.
Example 2
Input
999 1 500 250
Output
1000 1500 1750
999 + 1 = 1000, then 1500, then 1750: each line builds on the previous one.
Constraints
- 0 <= starting reading <= 1000000
- 0 <= each trip distance <= 1000
Hints
Hint 1 of 3
A plain let binding cannot change after it is set; to update a value you need let mut.
Hint 2 of 3
Start with let mut reading = start;, then reading += first; and print, and repeat for the other two trips.
Hint 3 of 3
Print with println!("{}", reading) after each addition so the three lines show the running value.
Solution
Show a reference solution and explanation
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
let mut read_num = || -> u64 { lines.next().unwrap().unwrap().trim().parse().unwrap() };
let mut reading = read_num();
let first = read_num();
let second = read_num();
let third = read_num();
reading += first;
println!("{}", reading);
reading += second;
println!("{}", reading);
reading += third;
println!("{}", reading);
}
Why it works
Rust bindings are immutable unless you write let mut, so the natural way to model something that changes over time, like an odometer, is one mutable variable updated in place. reading += first reads the current value, adds the trip and stores the result back in the same binding. Printing after each += shows the running total rather than three unrelated sums. The starter's read_num closure is declared mut for the same reason: each call advances the underlying line iterator, which is a change of state, and Rust makes that visible at the declaration.
Lesson for this exercise: Variables and Mutability in Rust