A Comprehensive Guide to Rust for, while, and loop Constructs

In Rust programming, a loop is used to conduct a code block multiple times. For example- to print a number 100 times, you can use a loop instead of writing the print statement continually.

In Rust Program, we can use three different keywords to conduct a code block multiple times :

  • loop

  • while loop

  • for loop

Loop Expression In Rust :

In Rust Program , we use the loop evolution to indefinitely conduct a block of code. If you use a loop, the code conduct inside of the loop code block doesn’t stop and runs forever.

The syntax of the loop evolution is:

loop {
    // code to execute
}

Now Let’s see an example-

fn main() {
    //  loop expression
    loop {
        println!("Loop forever!");
    }
}

Output :

Loop forever!
Loop forever!
Loop forever!
.
.
.

The below example code will print **“Loop forever!” **indefinitely unless the user end the program. Because the loop runs forever, it is also known as infinite loop.

Terminating Loop in Rust Programming

You use the break keyword to terminate a loop. Please for a example-

fn main() {
    // initiate an infinite loop
    loop {
        println!("Loop forever!");
        
        // stop infinite loop
        break;
    }
}

Output :

Loop forever!

Above, the break keyword terminates the loop. So that the println! macro is executed only once.

Example: Print First 10 Natural Numbers using Loop In Rust

fn main() {
    let mut number = 0;
    
    // infinite loop starts here
    loop {
        number += 1;
        println!("{}", number);
        
        if number >= 10 {
            // exit the loop
            break;
        }
    }
}

Output :

1
2
3
4
5
6
7
8
9
10

Please see above example, we have used a loop evolution to print the natural numbers. Above, the primary value of the number variable is 0.

Working of Loop In Rust Programming

Please see the below table where shows the working of the loop in each iteration.

Screenshot-2024-01-10-084318

Here, you see numbers 1 to 10 printed on the display

Working of loop and break in Rust Program

fn main() {
    let mut counter = 0;

    loop {
        println!("Counter: {}", counter);

        if counter == 5 {
            break; // Exit the loop when counter reaches 5
        }

        counter += 1;
    }
}

while Loop In Rust

We can use the while loop to conduct a code block till the condition is true. The syntax for the while evolution is below

while condition {
    // code block
}

// code block outside while loop

Above, the while loop evaluates the condition before advancing further.

If the condition appreciates to:

  • true - the code block inside the while loop is evolved and the condition is executed again
  • false - the loop terminates and the code block outside the while loop is evolved

Example: while Loop In Rust

fn main() {
    let mut counter = 1;

    // usage of while loop
    while counter < 6 {
        println!("{}", counter);
        
        counter += 1;
    }
}

Output :

1
2
3
4
5

In the example upon, we have a condition:

while counter < 6 {
    // code block
}

Above, the loop remain running till the counter variable is less than 6. under the loop, we are rising the value of the counter by 1.

After 5th iteration, the value of counter should be 6, so that the condition, counter < 6 becomes false and the loop is concluded.

Working of while Expression in Rust

Screenshot-2024-01-10-085900

Infinite while Loop In Rust

We can make a loop that never ends using the while evolution. Let’s check at an example-

fn main() {
    let counter = 1;

    // while loop with a condition that always evaluates to true
    while counter < 6 {
        println!("Loop forever!");
   }
}

Output :

Loop forever!
Loop forever!
Loop forever!
.
.
.

Please see Above example code will print “Loop forever!” indefinitely because of the condition counter < 6 constantly evaluates to true. Because you never increase the value of the counter variable under the loop. So, this program will run till the user terminates the program.

Example: Multiplication Table Using while Loop In Rust

fn main() {
    // variable to print multiplication table for
    let i = 2;
    
    // counter variable that starts at 1
    let mut j = 1;
    
    // while loop that runs for 10 iterations
    while j <= 10 {
        // multiply i and j
        let mult = i * j;
        
        // print multiplication result on each iteration
        println!("{} * {} = {}", i, j, mult);

        // increase value of counter variable j
        j += 1;
    }
}

Output :

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20

Nested while Loop In Rust

You can use a while loop under the body of another while loop. This is known as a shelter while loop. A shelter while loop looks like as :

while outer_condition {
    // outer code block 1

    while inner_condition {
        // inner code block
    }

    // outer code block 2
}

Now let’s print a model using a nested while loop

fn main() {
    // outer loop counter
    let mut i = 1;
    
    // outer loop
    while i <= 5 {
        // inner loop counter
        let mut j = 1;
        
        // inner loop
        while j <= 5 {
            print!("*");
            
            // increase inner loop counter
            j += 1;
        }
        
        println!("");
        
        // increase outer loop counter
        i += 1;
    }
}

Output :

*****
*****
*****
*****
*****

Please see above example,

  • The outer while loop repeatedly 5 times
  • The inner while loop under of the outer while loop also repeatedly 5 times
  • The inner while loop prints an asterisk(*) → print!(*) on every repeatedly
  • The inner while loop stops when the counter variable j comprehension to 6 as the inner condition evaluates to false
  • The outer while loop prints a modern line → println!("") on every repeatedly and goes to the next repeatedly which will initiate the inner while loop again
  • The outer while loop discontinue when the counter variable i reaches to 6 as the outer condition evaluates to false

for Loop In Rust

The for loop in Rust Programming used to iterate a range of numbers. The syntax of for loop is below:

for variable in lower_bound_number..upper_bound_number {
    // code block
}

Now, Let’s take a look at an example-

Example: for Loop In Rust

fn main() {
    // usage of for loop
    for i in 1..6 {
        println!("{}", i);
    }
}

Output :

1
2
3
4
5

In this above example, your print numbers 1 to 5 are using the for syntax. If you follow at the example closely, then we can see-

for i in 1..6 {
    println!("{}", i);
}

Above Example,

  • for - is the keyword to run any for loop
  • i - as known as the loop variable and will be a valid variable name
  • in - is the keyword maked to repeat over a series of values with for
  • 1..6 - is known as an repeat otherwise 1 is the lower bound and 6 is the upper bound. The yields values from 1 (inclusive) to 6 (exclusive) in steps of one.

Working of for Loop In Rust

Screenshot-2024-01-10-100842

How to use for to loop over an array or a list In Rust

Many programming languages, with Python, JavaScript, and others, we can use for loop to iterate over elements in an array or a list. The syntax might be vary simply depending on the programming language. But the primary structure remains similar. Now here are examples in Python and JavaScript below-

Python

my_list = [1, 2, 3, 4, 5]

# Using a for loop to iterate over the elements of the list
for element in my_list:
    print(element)

In above example, the variable element accept on each value in the list my_list during each iteration of the loop.

JavaScript

let myArray = [10, 20, 30, 40, 50];

// Using a for loop to iterate over the elements of the array
for (let i = 0; i < myArray.length; i++) {
    console.log(myArray[i]);
}

In above JavaScript, the loop beginning with initializing a variable (i in the case) to zero, and the loop run as long as the index is less than the length of the array. The index is incremented in every iteration.

Example: Sum of First 10 Natural Numbers using for Loop In Rust

fn main() {
    let mut sum = 0;
    
    // for loop to iterate over first 10 natural numbers
    for i in 1..11 {
        sum += i;
    }
    
    println!("Sum: {}", sum);
}

Output :

Sum: 55

Above the example, we found loop over the iterator 1..11, that yields values from 1 to 10. A sum variable is maked to sum all the values in each iteration. Now Finally, you print the sum of all the values.

break and continue In Rust

A loop fulfill a block of code multiple times. But, sometimes we might need to alter the flow of a loop by terminating its fulfill or skipping an iteration.

In cases, we can use the Rust break and continue to alter the normal perfection of loops. For example-

  • break - terminates the loop
  • continue - scamper the current iteration of the loop and foreword on to the next

break In Rust

In Rust Program, we can use the break keyword to terminate the perfection of any loop. For example-

while n < 10 {
    break;
}

Above, the while loop will end whensoever it encounters the break keyword, impartial of the loop condition (n < 10).

Example: break In Rust

fn main() {
    let mut number = 0;
    
    // loop starts here
    loop {
        number += 1;

        // condition to exit the loop
        if number > 5 {
            break;
        }

        println!("{}", number);        
    }
}

Output :

1
2
3
4
5

Working of break Keyword in Rust Program

Screenshot-2024-01-10-235106

break with Nested Loops In Rust

fn main() {
    let mut i = 1;
    
    // start of outer loop
    while i <= 5 {
        let mut j = 1;
     
        // start of inner loop
        while j <= 5 {
            print!("*");
            
            // condition to exit the inner loop
            if j == 3 {
                // terminate the inner loop
                break;
            }
            
            j += 1;
        }
        
        println!("");
        
        i += 1;
    }
}

Output :

***
***
***
***
***

Please see the above example, you have used the break keyword in the body of the inner while loop.

if j == 3 {
    // terminate the inner loop
    break;
}

continue In Rust Program

In Rust Program, you use the continue assertion to skip the current iteration of any loop and move to the next iteration. For example-

while n < 10 {
    if n == 5 {
        continue;
    }
}

Please see above example, the while loop will skip the current iteration when it visibility the continue keyword impartial of the loop condition (n<10).

Example: continue In Rust

fn main() {
    let mut number = 0;

    while number < 5 {
        number += 1;

        // condition to skip the iteration
        if number == 3 {
            continue;
        }

        println!("{}", number);
    }
}

Output :

1
2
4
5

In Above example, you can use the while evolution to print natural numbers. advertisement the use of the continue keyword,

if number == 3 {
    continue;
}

continue with Nested Loops In Rust Program

fn main() {
    let mut i = 1;
    
    // start of outer loop
    while i <= 5 {
        let mut j = 1;
            
        // start of inner loop
        while j <= 5 {
            j += 1;
            
            // condition to skip iteration of the inner loop
            if j == 3 {
                // move to the next iteration of the inner loop
                continue;
            }
            
            print!("*");
        }
        
        println!("");
        
        i += 1;
    }
}

Output :

****
****
****
****
****

Above example, you have used the continue keyword to skip an iteration of the inner while loop.

if j == 3 {
    // move to the next iteration of the inner loop
    continue;
}

break and continue with loop In Rust

You can also use break and continue simultaneously to control the flow of a program. For example-

fn main() {
    let mut number = 0;

    loop {
        number += 1;

        // condition to skip the iteration
        if number == 3 {
            continue;
        }
        
        // condition to exit the loop
        if number > 5 {
            break;
        }
        
        println!("{}", number);
    }
}

Output :

1
2
4
5

Above example, the continue keyword

if number == 3 {
    continue;
}

Likewise, the break keyword

if number > 5 {
    break;
}

enter, the loop if value of the number variable is greater than 5.

Previous
Conditional Logic in Rust - If-Else-Else-if Statements in RUST
Next
Mastering Rust Data Types: A Comprehensive Guide for Developers