0
0
Rustprogramming~10 mins

While loop 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 a while loop that counts down from 3 to 1.

Rust
let mut count = 3;
while [1] {
    println!("{}", count);
    count -= 1;
}
Drag options to blanks, or click blank then click option'
Acount >= 5
Bcount < 0
Ccount == 0
Dcount > 0
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a condition that never becomes false, causing an infinite loop.
Using count == 0 which stops the loop immediately.
2fill in blank
medium

Complete the code to print numbers from 1 to 5 using a while loop.

Rust
let mut num = 1;
while [1] {
    println!("{}", num);
    num += 1;
}
Drag options to blanks, or click blank then click option'
Anum <= 5
Bnum > 5
Cnum < 5
Dnum == 5
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using num < 5 which stops before printing 5.
Using num == 5 which runs only once.
3fill in blank
hard

Fix the error in the while loop condition to avoid an infinite loop.

Rust
let mut x = 0;
while [1] {
    println!("{}", x);
    x += 1;
    if x == 3 {
        break;
    }
}
Drag options to blanks, or click blank then click option'
Ax < 3
Bx > 3
Ctrue
Dx == 0
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using a condition that never becomes false without a break causes infinite loop.
Using x < 3 would also work but the task asks to fix the error with break.
4fill in blank
hard

Fill both blanks to create a while loop that prints even numbers less than 10.

Rust
let mut n = 0;
while [1] {
    println!("{}", n);
    n [2] 2;
}
Drag options to blanks, or click blank then click option'
An < 10
Bn <= 10
C+=
D-=
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using <= 10 includes 10 which is not less than 10.
Using -= 2 decreases n causing an infinite loop.
5fill in blank
hard

Fill all three blanks to create a while loop that collects numbers less than 5 into a vector.

Rust
let mut v = Vec::new();
let mut i = 0;
while [1] {
    v.push([2]);
    i [3] 1;
}
Drag options to blanks, or click blank then click option'
Ai < 5
Bi
C+=
Dv.len() < 5
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using v.len() < 5 in the condition can cause confusion.
Forgetting to increment i causes an infinite loop.