Loops and Ranges
Lesson 10 of 48 in Coddy's Rust for C++ Developers course.
C++ range-based for iterates an existing range; the classic three-part loop spells out initialization, condition and update. Rust for obtains an iterator from its operand. A numeric range such as 0..4 excludes its end, while 0..=4 includes it. continue skips the remainder of one iteration, and break exits the loop. A mutable counter is still useful with while, whose condition must be Boolean. Iterating an owned collection can consume it, whereas borrowing the collection yields borrowed elements; later lessons develop that distinction. Avoid assuming that the name of a loop variable is an index: iterating a vector normally gives its elements. Here the C++ loop and Rust loop deliberately skip different positions so their control flow must be traced independently.
Complete standalone C++17 program:
#include <iostream>
#include <array>
int main() {
for (int value : std::array<int, 3>{2, 4, 6}) {
if (value == 4) continue;
std::cout << value << '\n';
}
}Complete standalone Rust program:
fn main() {
for slot in 0..4 {
if slot == 2 { continue; }
println!("{}", slot);
}
let mut ticks = 2;
while ticks > 0 {
println!("tick={}", ticks);
ticks -= 1;
}
}Challenge
EasyCount calibration pulses. Input contains an exclusive upper bound from 0 to 10000. Required API: pub fn pulse_count(limit: u32) -> u32 counts positive multiples of 3 strictly less than limit; pub fn pulse_total(limit: u32) -> u32 sums those multiples. Zero is not a pulse. Output count total. Use iteration over a range; limits zero and one both produce 0 0. Implement the public API in pulses.rs. The supplied exercise.rs parses valid input and calls that API. Return the specified text without a trailing newline; the locked driver adds one newline. Do not print from the API. All input values satisfy the stated bounds.
Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.
Your code goes in exercise.rs, pulses.rs. main.rs holds the supplied input/output code and cannot be edited.
Try it yourself
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod pulses;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// BEGIN PUBLIC API PROBES
assert_eq!(pulses::pulse_count(16), 5);
assert_eq!(pulses::pulse_total(16), 45);
assert_eq!(pulses::pulse_count(0), 0);
assert_eq!(pulses::pulse_total(0), 0);
assert_eq!(pulses::pulse_count(3), 0);
assert_eq!(pulses::pulse_total(3), 0);
assert_eq!(pulses::pulse_count(6), 1);
assert_eq!(pulses::pulse_total(6), 3);
assert_eq!(pulses::pulse_total(16), 45);
// END PUBLIC API PROBES
println!("{}", exercise::solve(&input));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Rust for C++ Developers
1First Rust Programs
Run Rust ModulesOutput and CommentsModules and VisibilityBindings and TypesNumbers and CastsRecap: Storage Invoice4Ownership and Borrowing
Ownership and MovesShared BorrowsMutable BorrowsLifetimes and ViewsBorrowing Recap2Decisions and Loops
Boolean ConditionsIf ExpressionsMatch and EnumsLoops and RangesRecap: Charge Gate3Functions and Sequences
Functions and ReturnsArrays and SlicesVectors and IterationRecap: Record ReadingsPractice on your own: Online Rust compiler