What the exercise asks
The task is to add up every whole number from 14 to 73, including both ends, and print the total. There is no function to write here. The exercise is a few lines of code that run top to bottom.
The pattern is one of the most common in programming: an accumulator. A variable starts at zero, a loop visits each number in turn, and each pass adds that number to the variable. When the loop is over, the variable holds the total.
The for loop and ranges in Rust
A Rust for loop walks over anything that can produce a sequence of values. The usual way to write a sequence of integers is a range:
14..73is a half-open range. It starts at 14 and stops before 73, so its last value is 72.14..=73is an inclusive range. Its last value is 73.
for i in 14..=16 {
println!("{}", i);
}
This prints 14, 15 and 16 on separate lines. The loop variable i is created fresh for each pass, so it needs no let and no mut. The loop sets its value itself, and it disappears when the loop ends.
Step by step
- Declare the accumulator. Write
let mut sum = 0;. Bindings in Rust are immutable by default, and this one changes on every pass, so it needsmut. The compiler picksi32forsum, which is wide enough for this total. - Open the loop. Use
for i in 14..=73 {. The inclusive range matters: with14..73the loop would skip 73. - Add to the total. Inside the loop, write
sum += i;. This is shorthand forsum = sum + i;. - Print after the loop. A
println!placed after the closing brace runs once, when all 60 numbers have been added.
The solution in Rust
let mut sum = 0;
for i in 14..=73 {
sum += i;
}
println!("{}", sum);
The program prints:
2610
That matches the formula for a run of consecutive integers: the count is 60, and the average of the first and last numbers is (14 + 73) / 2 = 43.5, so the total is 60 * 43.5 = 2610. The loop gets the same answer by brute force.
Common mistakes
- Leaving out
=. With14..73the loop stops at 72, and the program prints 2537 instead of 2610. The difference is the missing 73. - Forgetting
mut. Without it,sum += i;is a compile error, because the binding cannot be assigned to again. - Printing inside the loop. A
println!inside the braces prints a running total on each of the 60 passes, instead of one final line. - Starting the accumulator at the wrong value. It must start at 0, the value that changes nothing when you add to it. Starting at 1 would make the answer 2611.
- Declaring the variable inside the loop. A
sumdeclared in the body would be new on every pass and would disappear at the closing brace, so theprintln!after the loop could not see it.
Key takeaways
- An accumulator is declared before the loop, starts at the neutral value (0 for sums) and is updated inside it.
a..bexcludesb, whilea..=bincludes it.- A variable that changes needs
let mut. - The loop variable of a
forloop is created by the loop itself.
