Jump to content

Programming Fundamentals/Loops/Rust

From Wikiversity

loops.rs

[edit | edit source]
// This program demonstrates While, Do, and For loop counting using
// user-designated start, stop, and increment values.
//
// References:
// https://doc.rust-lang.org/book/ch03-02-data-types.html
// https://doc.rust-lang.org/reference/expressions/loop-expr.html

use std::io;

fn main() {
    let start = get_value("starting");
    let stop = get_value("ending");
    let increment = get_value("increment");

    process_while_loop(start, stop, increment);
    process_do_loop(start, stop, increment);
    process_for_loop(start, stop, increment);
}

fn get_value(name:&str) -> u32 {
    println!("Enter {} value:", name);
    let mut line = String::new();
    io::stdin().read_line(&mut line).expect("Error reading line");
    let value:u32 = line.trim().parse().expect("Not a valid number");
    return value;
}

fn process_while_loop(start:u32, stop:u32, increment:u32) {
    println!("While loop counting from {} to {} by {}:",
        start, stop, increment);

    let mut count = start;
    while count <= stop {
        println!("{}", count);
        count += increment;
    }
}

fn process_do_loop(start:u32, stop:u32, increment:u32) {
    println!("Do loop counting from {} to {} by {}:",
        start, stop, increment);

    let mut count = start;
    loop {
        println!("{}", count);
        count += increment;
        if count > stop {
            break;
        }
    }
}

fn process_for_loop(start:u32, stop:u32, increment:u32) {
    println!("For loop counting from {} to {} by {}:",
        start, stop, increment);

    for count in (start..stop + 1).step_by(increment as usize) {
        println!("{}", count);
    }
}

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own Rust compiler / interpreter / IDE.

See Also

[edit | edit source]