Perform the following steps:
- Create a file named looping.rs and enter the following code in the script.
- In the main function, perform a looping operation on the mutable variable x, which is initially assigned to the integer value of 1.
- Define a loop statement, which is an infinite iterative statement, and check the various conditions inside its scope:
fn main() {
// mutuable variable whose value can be changed
let mut x =1;
println!(" Loop even numbers ");
// Continously loops
loop {
// Check if x is an even number or not
if (x % 2 == 0){
println!("{}",x);
x += 1;
// goes to the loop again
continue;
}
// exit if the number is greater than 10
if (x > 10) {
break;
}
// increment the number when not even
x+=1;
}
- Create a mutable variable y and assign it to the integer value 1 , and define a while loop with the y < 10 condition:
let mut y = 1;
// while loop
println!("while 1 to 9 ");
while y < 10 {
println!("{}",y );
y +=1;
}
- Perform a similar operation as for the while loop. Here, use the for loop to iterate over the 1 to 9 range on the mutable variable z, which is initially assigned to the value 1:
let mut z = 1;
//for loop
println!(" For 1 to 9");
for z in 1 .. 10 {
println!("{}",z );
}
}
You should get the following screenshot as output upon running the preceding code: