In this tutorial you will learn about the Rust While Loop and its application with practical example.
Rust While Loop
The while loop will execute a block of statement as long as a test expression is true. While loop is useful when the number of iterations can not be predicted beforehand. The while loop evaluates test expression at beginning of each pass.
Rust While Loop Flow Diagram
Syntax:-
1 2 3 |
while condition { // loop body } |
Here, Condition is a Boolean expression that results in either True or False, if it results in True then statements inside loop body are executed and condition is evaluated again. This process is repeated until the condition is evaluated to False. If the condition results in False then execution is skipped from loop body and while loop is terminated.
Example:-
1 2 3 4 5 6 7 8 9 10 |
fn main() { let mut ctr = 1; let max_ctr = 5; println!("W3Adda - Rust While Loop"); while ctr <= max_ctr { println!("Hello World! Value Is :{}", ctr); ctr = ctr + 1; } println!("Out of while loop"); } |
Here, we have initialized ctr and max_ctr to 1 and 5 respectively, in the next statement we have while loop, that checks the condition ctr <= max_ctr for each of the iteration. If the test condition returns True, the statements inside loop body are executed and if test condition returns False then the while loop is terminated. Inside the loop body we have incremented the ctr value by one for each if the iteration. When we run the above swift program, we see the following output –
Output:-
Rust infinite while loop
If you need an infinite loop, you may use while loop as follows –
Syntax:-
1 2 |
while true { } |
However, loop
is better suited for infinite loop, while loop should be avoided for this case.