On this page
article
Break Statement
Break Statement
What Is a break
Statement?
The break statement terminates the loop. It is generally placed inside a conditional statement so that the loop terminates if the associated condition is true.
Break statement is valid in case of while, for and loop.
Using With a for Loop
Below is an example of break expression, using a for loop.
- The range defined in the for loop is from 0 to 10.
- Within the for loop :
- The value of
i
is printed - When the value of
i
is equal to5
, the loop terminates
- The value of
output
Using With a while Loop
Below is an example of break expression, using a while loop.
- A mutable variable i is defined
- A boolean variable found is defined
Within the while loop body :
- The value of i is printed
- When the value of
i
is equal to5
, the loop terminates
output
Using With a loop
Below is an example of break expression, using a loop.
- A mutable variable i is defined
- Within the loop body:
- The value of i is printed
- When the value of
i
is equal to4
, the loop terminates
The infinite loop is turned into a “manageable” loop.
Output
Quiz
Test your understanding of how break statement works in Rust.
Last updated a year ago.