Open In App

Rust – While Loop

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Loops in Rust come into use when we need to repeatedly execute a block of statements. Loops are also useful when we need to iterate over a collection of items. In Rust, we have various kinds of loops, including loops, while loops, and for loops. The while loop is the most common loop in Rust. The loop keyword is used to create a loop. While loops are similar to while loops in other languages. In a while loop, we have a condition and a block of statements. The condition is checked at the start of each iteration of the loop. If the condition is true, the block of statements is executed and the loop continues. If the condition is false, the loop terminates. We will cover the while loop in detail in this article.

While loop

Note:

The while loop comes under the flow control category.

Syntax:

while condition {

// code block

// counter increment

}

Let’s dig into the while loop.

  1. The while keyword is used to create a loop. It is followed by a condition.
  2. The condition should be valid and it should be followed by a block of code. If the condition is true, the block of code is executed. If the condition is false, the loop terminates.
  3. The code block or the statements is a group of instructions or operations that we perform after entering the loop. Here we have the task that we want to repeat.
  4. For the counter condition or the update expression after executing the loop body, we need to increment the loop variable to keep the loop running. It is a necessary condition, without this, the while loop might not end and become an infinite loop.

Let’s take some examples to better understand the while loop in Rust

Example 1:

Rust




// while loop in Rust
fn main(){
    // creating a counter variable
    let mut n = 1;
 
    // loop while n is less than 6
    while n < 6 {
        // block of statements
 
        println!("Hey Geeks!!");
 
        // increment counter
        n += 1;
 
    } // exiting while loop
}


In the above piece of code, we have created a simple program where we are printing the string “Hey Geeks!!” multiple times using the while loop. 

Output: 

figure 1: While loop

Example 2: To multiply 2 with every number from 1 to 10 using the while loop.

Rust




// Rust program to multiply numbers
fn main(){
 
    // number to multiply with
    let num = 2;
     
    // A mutable variable i
    let mut i = 1; //
 
    // while loop run till i is less than 11
    while i < 11 {
         
        // printing the multiplication
        println!("{}", num*i);
 
        // increment counter
        i += 1;
    }
}


Output: 

Figure 2: While loop



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads