Rust FizzBuzz Loop Programming

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we learn about the while keyword, which is used to create a loop that continues executing as long as a specified condition is true. To illustrate its usage, we write a program in Rust called FizzBuzz. The program uses a while loop to iterate through numbers from 1 to 100. Inside the loop, it checks if the current number is divisible by 3 and 5 (i.e., a multiple of 15) and prints "fizzbuzz" in such cases. If the number is only divisible by 3, it prints "fizz", and if it is only divisible by 5, it prints "buzz". For all other numbers, it simply prints the number itself. The loop continues until the counter variable reaches 101, incrementing it after printing each number or label.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/variable_declarations -.-> lab-99307{{"`Rust FizzBuzz Loop Programming`"}} rust/mutable_variables -.-> lab-99307{{"`Rust FizzBuzz Loop Programming`"}} rust/string_type -.-> lab-99307{{"`Rust FizzBuzz Loop Programming`"}} rust/function_syntax -.-> lab-99307{{"`Rust FizzBuzz Loop Programming`"}} rust/expressions_statements -.-> lab-99307{{"`Rust FizzBuzz Loop Programming`"}} end

while

The while keyword can be used to run a loop while a condition is true.

Let's write the infamous FizzBuzz using a while loop.

fn main() {
    // A counter variable
    let mut n = 1;

    // Loop while `n` is less than 101
    while n < 101 {
        if n % 15 == 0 {
            println!("fizzbuzz");
        } else if n % 3 == 0 {
            println!("fizz");
        } else if n % 5 == 0 {
            println!("buzz");
        } else {
            println!("{}", n);
        }

        // Increment counter
        n += 1;
    }
}

Summary

Congratulations! You have completed the While lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like