Search⌘ K

Solution Review 2: Count Iterations of a Loop Until a Condition

Understand how to implement and count iterations within a while loop in Rust by using mutable variables and loop conditions. This lesson helps you grasp controlling loop execution and tracking iteration counts in Rust programming.

We'll cover the following...

Solution:

Rust 1.40.0
fn test(mut x:i32) {
// define a mutable variable
let mut count = 0;
// define a while loop
while x >= 0 {
x = x - 3; // decrement the value of x by 3
count = count + 1;
}
println!("{}", count);
}
fn main(){
print!("Iterations when x = 21 :");
test(21);
print!("Iterations when x = 33 :");
test(33);
}

Explanation

  • On line 3, a mutable variable count is initialized with 0.
  • while
...