Control Statements
Rust While Loop
While loop
A conditional loop is called a “while-loop.” The conditional loop is used in programs that require condition evaluation. The loop is carried out when the condition is met; if not, it is ended.
Syntax of 'while loop'
while condition
//block statements;
The while loop in the syntax above assesses the condition. Block statements are carried out if the condition is true; else, the loop is ended. ‘loop’, ‘if’, ‘else’, or ‘break’ statements can be combined with this built-in construct in Rust.
Flow diagram of while loop
Example
fn main()
{
let mut i=1;
while i<=10
{
print!("{}", i);
print!(" ");
i=i+1;
}
}
Output:
1 2 3 4 5 6 7 8 9 10
Since ‘i’ in the example above is a mutable variable, its value is changeable. The while loop runs until ‘i’s’ value is either equal to or less than 10.
Example
fn main()
{
let array=[10,20,30,40,50,60];
let mut i=0;
while i<6
{
print!("{}",array[i]);
print!(" ");
i=i+1;
}
}
Output:
10 20 30 40 50 60
The while loop is used to iterate through the items of an array in the example above.
Disadvantages of while loop:
- The issue may arise from a while loop if the index length is off.
- Additionally, it is sluggish because every time this loop is executed, the compiler inserts runtime code to carry out the conditional check.