Code Logo

Return from loop with break

Published at25 Jul 2026
Rust Functions Easy 0 views
Like0

Write a Rust function that uses a loop with break to find the smallest multiple of a number n that is at least 10. Repeatedly add n to itself until the value reaches or exceeds 10, then return that value using break. The loop construct in Rust can return a value using the break keyword followed by an expression: break value.

Rust's loop creates an infinite loop that must be exited explicitly with break. Unlike while or for loops, loop doesn't have a condition. Instead, you place break statements inside the loop body to exit when a condition is met. The break statement can optionally return a value from the loop, making loop an expression that evaluates to the break value.

This pattern of loop with break returning a value is unique to Rust among mainstream languages. In most other languages, break is a statement and cannot return a value. Rust's expression-oriented design allows loop blocks to produce values, enabling concise implementations of search algorithms that would require explicit state variables in other languages.

Time complexity is O(k) where k is the number of additions needed to reach the target. Space complexity is O(1). The loop structure compiles to efficient jump instructions with minimal overhead.

Edge cases include the input already being at least 10 (loop body executes break on first iteration), ensuring the sum variable starts at n and increments by n each iteration, and that the break value is correctly assigned to the result variable.

Example Input & Output

Example 1
Input
3
Output
12
Explanation

3+3+3+3 = 12 >= 10

Example 2
Input
5
Output
10
Explanation

5+5 = 10 >= 10

Example 3
Input
4
Output
12
Explanation

4+4+4 = 12 >= 10

Example 4
Input
7
Output
14
Explanation

7 < 10, 7+7=14 >= 10, break with 14

Example 5
Input
10
Output
10
Explanation

10 >= 10, break immediately

Algorithm Flow

Recommendation Algorithm Flow for Return from loop with break
Recommendation Algorithm Flow for Return from loop with break

Solution Approach

fn solution(n: i32) -> i32 {
    let mut current = n;
    loop {
        if current >= 10 {
            break current;
        }
        current += n;
    }
}

Best Answers

rust - Approach 1
fn solution(n: i32) -> i32 {
    let mut current = n;
    loop {
        if current >= 10 {
            break current;
        }
        current += n;
    }
}