0
0
Rustprogramming~5 mins

While loop in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a while loop in Rust?
A while loop in Rust repeats a block of code as long as a given condition is true. It checks the condition before each repetition.
Click to reveal answer
beginner
How do you write a basic while loop that counts from 1 to 5 in Rust?
You can write it like this:<br><pre>let mut count = 1;
while count <= 5 {
    println!("{}", count);
    count += 1;
}</pre>
Click to reveal answer
beginner
What happens if the condition in a while loop is initially false?
The code inside the while loop will not run at all because the condition is checked before the loop starts.
Click to reveal answer
intermediate
How can you stop an infinite while loop in Rust?
You can stop it by using a break statement inside the loop when a certain condition is met.
Click to reveal answer
beginner
Why do you need to declare the loop variable as mut in a while loop?
Because the variable changes its value inside the loop, it must be mutable (mut) so Rust allows updating it.
Click to reveal answer
What keyword starts a while loop in Rust?
Arepeat
Bwhile
Cfor
Dloop
What happens if the while loop condition is false at the start?
AThe loop does not run at all
BThe loop runs once
CThe loop runs infinitely
DThe program crashes
How do you stop a while loop early inside the loop?
Aexit
Bcontinue
Cstop
Dbreak
Why must the loop counter be declared with mut?
ABecause it changes value inside the loop
BBecause Rust requires all variables to be mutable
CBecause it is a constant
DBecause it is a string
Which of these is a correct while loop condition to count from 1 to 3?
Awhile count == 3
Bwhile count < 3
Cwhile count <= 3
Dwhile count > 3
Explain how a while loop works in Rust and give a simple example.
Think about counting numbers using a variable that changes.
You got /4 concepts.
    Describe how to stop an infinite while loop in Rust.
    Imagine you want to stop the loop when a number reaches 10.
    You got /3 concepts.