0
0
Rustprogramming~10 mins

Loop construct in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an infinite loop using the correct Rust keyword.

Rust
fn main() {
    [1] {
        println!("Hello, world!");
        break;
    }
}
Drag options to blanks, or click blank then click option'
Aif
Bwhile
Cfor
Dloop
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'while' without a condition causes a syntax error.
Using 'for' requires an iterator, so it won't compile here.
2fill in blank
medium

Complete the code to loop over numbers from 1 to 5 and print each number.

Rust
fn main() {
    for i in [1] {
        println!("{}", i);
    }
}
Drag options to blanks, or click blank then click option'
A1..=5
B1..5
C0..5
D0..=5
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using '1..5' excludes 5, so it prints only 1 to 4.
Using '0..5' starts from 0, which is not wanted here.
3fill in blank
hard

Fix the error in the loop that should print numbers 0 to 4.

Rust
fn main() {
    let mut count = 0;
    while [1] {
        println!("{}", count);
        count += 1;
    }
}
Drag options to blanks, or click blank then click option'
Acount <= 5
Bcount < 5
Ccount > 5
Dcount == 5
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using 'count <= 5' prints 0 to 5, one extra number.
Using 'count == 5' causes the loop to never run.
4fill in blank
hard

Fill both blanks to create a loop that prints even numbers from 2 to 10.

Rust
fn main() {
    for num in [1] {
        if num [2] 2 == 0 {
            println!("{}", num);
        }
    }
}
Drag options to blanks, or click blank then click option'
A2..=10
B1..=10
C%
D==
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using '==' instead of '%' causes a syntax error in the condition.
Using '1..=10' includes odd numbers starting at 1.
5fill in blank
hard

Fill all three blanks to create a loop that collects squares of numbers greater than 3 from 1 to 5.

Rust
fn main() {
    let squares: Vec<i32> = (1..=5)
        .filter(|&[1]| [1] [2] 3)
        .map(|[3]| [3] * [3])
        .collect();
    println!("{:?}", squares);
}
Drag options to blanks, or click blank then click option'
Ax
B>
D<
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using different variable names in filter and map causes errors.
Using '<' instead of '>' filters wrong numbers.