Keep a running total
Start at zero and add each value as you reach it.
Simple example
Start2 + 4
Result6
fn main() {
let mut total: i64 = 0;
total += 2;
total += 4;
println!("{}", total);
}
6
Advertisements
Everyday examples
Three classes donate 5, 2 and 4 books. How many books can the library put on its shelves?
Start5 + 2 + 4
Result11
fn main() {
let books: [i64; 3] = [5, 2, 4];
let mut total: i64 = 0;
let mut i: i64 = 0;
while i < 3 {
total += books[(i) as usize];
i += 1;
}
println!("{}", total);
}
11