While and For Range in Rust Programming


We know that Rust provides a loop keyword to run an infinite loop. But the more traditional way to run loops in any programming language is with either making use of the while loop or the for range loop.

While Loop

The while loop is used to execute a code of block until a certain condition evaluates to true. Once the condition becomes false, the loop breaks and anything after the loop is then evaluated. In Rust, it is pretty much the same.

Example

Consider the example shown below:

Live Demo

fn main() {
   let mut z = 1;
   while z < 20 {
      if z % 15 == 0 {
         println!("fizzbuzz");
      } else if z % 3 == 0 {
         println!("fizz");
      } else if z % 5 == 0 {
         println!("buzz");
      } else {
         println!("{}", z);
      }
      z += 1;
   }
}

In the above code, we are making use of the while keyword which is immediately followed by a condition ( z < 20 ) and as long as that condition is evaluated to true, the code inside the while block will run.

Output

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19

For Range

The for in constructor provided by the Rust compiler is used to iterate through an Iterator. We make use of the notation a..b, which returns a (inclusive) to b(exclusive) in the step of one.

Example

Consider the example shown below:

Live Demo

fn main() {
   for z in 1..20 {
      if z % 15 == 0 {
         println!("fizzbuzz");
      } else if z % 3 == 0 {
         println!("fizz");
      } else if z % 5 == 0 {
         println!("buzz");
      } else {
         println!("{}", z);
      }
   }
}

Output

1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19

Updated on: 05-Apr-2021

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements