0
0
Rustprogramming~5 mins

Loop with break in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the break keyword do inside a Rust loop?
The break keyword immediately stops the loop and exits it, continuing with the code after the loop.
Click to reveal answer
intermediate
How can you use break to return a value from a loop in Rust?
You can add a value after break, like break value;. This value becomes the result of the loop expression.
Click to reveal answer
intermediate
What happens if you use break inside a nested loop?
The break only exits the innermost loop where it is called, not outer loops.
Click to reveal answer
beginner
Can break be used in while and for loops in Rust?
Yes, break works in all loop types: loop, while, and for to stop the loop early.
Click to reveal answer
beginner
Example: What will this Rust code print?<br><pre>let mut count = 0;<br>loop {<br>  count += 1;<br>  if count == 3 {<br>    break;<br>  }<br>}<br>println!("{}", count);</pre>
It will print 3 because the loop increments count until it reaches 3, then breaks out of the loop.
Click to reveal answer
What does break do inside a Rust loop?
ADoes nothing
BStops the loop immediately and exits it
CRestarts the loop from the beginning
DSkips the current iteration and continues
How do you return a value from a Rust loop using break?
AUse <code>break value;</code> to return a value
BYou cannot return a value from a loop
CUse <code>return value;</code> inside the loop
DUse <code>continue value;</code>
If you have nested loops, which loop does break exit?
AThe outermost loop
BAll loops at once
CThe innermost loop where <code>break</code> is called
DNone of the loops
Can break be used in a for loop in Rust?
ANo, only in <code>loop</code>
BOnly in functions
COnly in <code>while</code> loops
DYes, it works in <code>for</code> loops
What will this code print?<br>
let mut i = 0;<br>while i < 5 {<br>  if i == 2 {<br>    break;<br>  }<br>  i += 1;<br>}<br>println!("{}", i);
A2
B5
C0
DInfinite loop
Explain how the break keyword works in Rust loops and how it can be used to return a value.
Think about how to stop a loop early and get a result from it.
You got /3 concepts.
    Describe what happens when break is used inside nested loops in Rust.
    Consider which loop the break applies to.
    You got /3 concepts.