Solution Review 2: Count Iterations of a Loop Until a Condition
This lesson gives a detailed solution review of the challenge in the previous lesson.
We'll cover the following...
Solution:
Press + to interact
fn test(mut x:i32) {// define a mutable variablelet mut count = 0;// define a while loopwhile x >= 0 {x = x - 3; // decrement the value of x by 3count = 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 with0
.
while
construct