While Loop
Part of the Fundamentals section of Coddy's Rust journey — lesson 38 of 75.
A while loop is different from the for loop. A for loop allows us to iterate over a specific range, whereas a while loop allows us to keep iterating as long as a certain condition is met.
To use a while loop write:
while condition {
code
}The code will execute only if the condition is true.
There are many use cases where a while would solve the problem, but the for loop would not.
Challenge
BeginnerWrite a program that gets one input, a double number.
Use a while loop to divide the input by 2 as long as the number is bigger or equal to 3.5.
Print the first number that is smaller than 3.5.
Cheat sheet
A while loop executes code as long as a condition is true:
while condition {
code
}Unlike for loops that iterate over a specific range, while loops continue until the condition becomes false.
Try it yourself
use std::io;
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let mut number: f64 = input.trim().parse().unwrap();
// Write your code below
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input