CodeBlanks Logo Icon CodeBlanks

while loop

Loop while a condition holds with while.

The while loop

while repeats as long as the condition is true; the condition is checked at the start of every iteration:

let mut geri = 3;
while geri > 0 {
    println!("{geri}...");
    geri -= 1;
}
println!("kalkış!");

To walk a collection by index, for is preferred over while; it removes the risk of index mistakes and the cost of bounds checks.

Counting digits

while is natural for work whose number of iterations isn't known in advance. For example, summing a number's digits:

let mut n = 4096;
let mut toplam = 0;
while n > 0 {
    toplam += n % 10;
    n /= 10;
}
println!("{toplam}");  // 19

Practice Digit count

Write fn basamak(mut n: u64) -> u32: compute the digit count by dividing the number by 10 in a while n >= 10 loop (1 for 0). Print basamak(0), basamak(7) and basamak(123456) on one line.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn basamak(mut n: u64) -> u32 {
    let mut sayi = 1;
    while n >= 10 {
        n /= 10;
        sayi += 1;
    }
    sayi
}

fn main() {
    println!("{} {} {}", basamak(0), basamak(7), basamak(123456));
}

Expected output

1 1 6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between <code>while</code> and <code>loop</code>?

  • There is no difference
  • loop is slower
  • while checks a condition at the start of each iteration; loop repeats unconditionally Correct answer
  • while returns a value

Explanation: Returning a value with break exists only for loop; while always produces ().

2 Conditional loop

Question
____ n > 1 {
    n /= 2;
    adim += 1;
}
Answer
while n > 1 {
    n /= 2;
    adim += 1;
}

Explanation: while repeats the body as long as the condition is true.

3 Loop and use

Term Meaning
loop Unconditional, with break
while While a condition holds
for Iterating a collection / range
n /= 10 Drops the last digit

All lessons in Beginner