Menu
CoddyTech

Loops and Ranges

Lesson 10 of 48 in Coddy's Rust for Java Developers course.

Java counting loops spell out initialization, condition and update. Rust for consumes an iterable, often a range. a..b excludes the end; a..=b includes it. These are different values rather than punctuation variants. A loop variable receives each value in order, and the accumulator needs a mutable binding if its value changes.

Rust also has while and unconditional loop. break leaves the nearest loop; continue skips to its next iteration. A loop can yield a value with break value, which Java's ordinary loop statements do not do. The small factorial example uses an inclusive range so the final factor participates. An empty range executes its body zero times, leaving the initial accumulator unchanged.

Java: complete program

class Main {
    public static void main(String[] args) {
        int product = 1;
        for (int n = 1; n <= 4; n++) product *= n;
        System.out.println(product);
    }
}

Rust: complete program

fn main() {
    let mut product = 1;
    for n in 1..=4 { product *= n; }
    println!("{}", product);
}

Pitfall: replacing an inclusive range with an exclusive one omits the last factor.

challenge icon

Challenge

Easy

Count 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));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler