0
0
Rustprogramming~20 mins

For loop in Rust - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Rust For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
What is the output of this Rust for loop?
Consider the following Rust code. What will it print?
Rust
fn main() {
    let mut sum = 0;
    for i in 1..5 {
        sum += i;
    }
    println!("{}", sum);
}
AError: cannot add i to sum
B15
C14
D10
Attempts:
2 left
๐Ÿ’ก Hint
Remember that 1..5 in Rust means 1 up to but not including 5.
๐Ÿง  Conceptual
intermediate
1:30remaining
How many times does this Rust for loop run?
How many iterations will this loop execute? for x in (0..10).step_by(3) { println!("{}", x); }
A4
BError: step_by requires usize
C10
D3
Attempts:
2 left
๐Ÿ’ก Hint
Count numbers from 0 to 9 stepping by 3.
โ“ Predict Output
advanced
2:30remaining
What is the output of this nested for loop?
Analyze the output of this Rust code snippet:
Rust
fn main() {
    for i in 1..3 {
        for j in 1..=i {
            print!("{}{} ", i, j);
        }
    }
}
A11 21
B11 12 21 22
C11 21 22
D12 22
Attempts:
2 left
๐Ÿ’ก Hint
Remember that 1..3 means 1 and 2, and 1..=i includes i.
๐Ÿ”ง Debug
advanced
2:00remaining
What error does this Rust for loop code produce?
Identify the error when running this code:
Rust
fn main() {
    let mut numbers = vec![1, 2, 3];
    for num in numbers.iter() {
        numbers.push(*num + 1);
    }
}
ACompile error: cannot borrow `numbers` as mutable while iterating
BSyntax error: missing semicolon
CNo error, prints numbers
DCompile error: cannot move out of `numbers`
Attempts:
2 left
๐Ÿ’ก Hint
Think about modifying a vector while looping over it.
๐Ÿš€ Application
expert
3:00remaining
What is the final value of `result` after this loop?
Given this Rust code, what is the value of `result` after the loop finishes?
Rust
fn main() {
    let mut result = 1;
    for i in (1..=4).rev() {
        if i % 2 == 0 {
            result *= i;
        }
    }
    println!("{}", result);
}
A24
B8
C4
D0
Attempts:
2 left
๐Ÿ’ก Hint
Multiply only even numbers from 4 down to 1.