Menu
Coddy logo textTech

Loops as Expressions

Part of the Logic & Flow section of Coddy's Rust journey — lesson 5 of 66.

In most programming languages, loops are statements that execute code repeatedly. But Rust has a unique feature: loops can also be expressions that return a value. This means you can assign the result of a loop to a variable.

To return a value from a loop, you use break followed by the value you want to return:

let result = loop {
    // some condition checking
    if condition_met {
        break 42; // exit loop and return 42
    }
};

Here's a practical example that finds the first even number starting from 10:

let mut counter = 10;

let first_even = loop {
    if counter % 2 == 0 {
        break counter; // return the even number
    }
    counter += 1;
};

println!("First even number: {}", first_even);

The loop continues until it finds an even number, then uses break counter to exit the loop and return that number. The returned value gets assigned to first_even.

challenge icon

Challenge

Easy

You will receive a starting number as input. Read the input, convert it to an integer, and use a loop as an expression to find the first number divisible by 7 starting from that number.

Requirements:

  • Use a loop expression that returns a value
  • Start checking from the input number
  • Find the first number that is divisible by 7 (remainder is 0 when divided by 7)
  • Use break to return the found number from the loop
  • Print the result

Input: A single integer representing the starting number

Output: Print the first number divisible by 7 starting from the input number

Cheat sheet

In Rust, loops can be expressions that return a value. Use break followed by a value to exit the loop and return that value:

let result = loop {
    if condition_met {
        break 42; // exit loop and return 42
    }
};

Example finding the first even number:

let mut counter = 10;

let first_even = loop {
    if counter % 2 == 0 {
        break counter; // return the even number
    }
    counter += 1;
};

println!("First even number: {}", first_even);

Try it yourself

use std::io;

fn main() {
    // Read input
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");
    let start_number: i32 = input.trim().parse().expect("Invalid input");
    
    // TODO: Write your code below
    // Use a loop expression to find the first number divisible by 7
    
    
    // Print the result
    // println!("{}", result);
}
quiz iconTest yourself

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

All lessons in Logic & Flow