More Than Once!
If you squint at the program in the previous lesson, our while
loop isn’t much of a loop, as it still only runs the body once. Can we modify it so that it prints, “Inside the while loop,” four times, while only using one println!
call? Yes, we can!
Challenge exercise: I’ll show you the answer in a second, but try to figure out the solution yourself. If you’re stumped, here’s a hint; instead of a mutable bool
variable, you’ll probably want a mutable i32
variable. Remember to use the mut
keyword.
Our mutable keep_going
only has two states: true
and false
. That’s too limiting for trying to get the loop to run four times. Instead, let’s keep a counter of how many times we’ve gone through the loop already:
Get hands-on with 1400+ tech skills courses.