DEV Community

RealACJoshua
RealACJoshua

Posted on

๐Ÿš€ Rust Basics 3: Control Flow, Conditional Statements, and Loops ๐Ÿฆ€

Welcome back to RUST BASICS. In this 3rd post of our 7-part journey, weโ€™ll tackle control flow in Rust. Youโ€™ll learn how to use if/else statements, match expressions, and loops to add logic and repetition to your programs.


Step 1: If/Else Statements

Control the flow of your program using if, else if, and else.

Syntax:

fn main() {
    let number = 10;

    if number > 0 {
        println!("The number is positive.");
    } else if number < 0 {
        println!("The number is negative.");
    } else {
        println!("The number is zero.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

If number > 0, the first block runs.

If number < 0, the second block runs.

If none of the conditions are met, the else block runs.

Rust Tip: Conditions in Rust must evaluate to a boolean (true or false). Unlike some other languages, you cannot use if number (it must be if number != 0, for example).


Step 2: Using If as an Expression

What does "if as an expression" mean?

Unlike in some other programming languages, in Rust, if can be used to produce a value โ€” not just control flow. This means you can assign the result of an if statement to a variable.

This is possible because everything in Rust is an expression. An expression returns a value, while a statement (like let x = 5;) performs an action but does not return a value.


Example : Assigning the Result of if to a Variable

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 10 };

    println!("The value of number is: {}", number);
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

let number = if condition { 5 } else { 10 };

A. Rust checks if condition is true or false.

If condition is true, Rust returns 5, and that value is assigned to number.

If condition is false, Rust returns 10, and that value is assigned to number.

B. Since the if block returns a value, you don't need to explicitly assign a value to number. Rust automatically "returns" the last value of the block.

C. The final result is printed as:
"The value of number is: 5" (because condition is true).


Step 3: Match Expressions

match is a powerful control flow tool similar to switch statements in other languages.

Example:

fn main() {
    let day = "Monday";

    match day {
        "Monday" => println!("Start of the work week!"),
        "Friday" => println!("Weekend is near!"),
        "Saturday" | "Sunday" => println!("Itโ€™s the weekend!"),
        _ => println!("Just another day!"),
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

"Saturday" | "Sunday" means "if it's Saturday or Sunday, do this."

The underscore _ acts as a catch-all for any other value that doesn't match the cases.


Step 4: Loops in Rust

Rust provides three types of loops:

  1. loop - Infinite loop (until break is used).

  2. while - Loops while a condition is true.

  3. for - Loops over a range, array, or collection.


1๏ธโƒฃ Loop (Infinite Loop)

fn main() {
    let mut counter = 0;

    loop {
        counter += 1;
        println!("Count: {}", counter);

        if counter == 5 {
            break; // Exits the loop
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

The loop runs infinitely until break is called.

This is useful when you don't know how many iterations are needed.


2๏ธโƒฃ While Loop

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }

    println!("LIFTOFF ๐Ÿš€");
}

Enter fullscreen mode Exit fullscreen mode

Explanation:

While the number is not zero, the loop runs.

When number becomes zero, the loop exits and prints "LIFTOFF ๐Ÿš€".


3๏ธโƒฃ For Loop (Range)

fn main() {
    for number in 1..5 {
        println!("Number: {}", number);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

1..5 is a range that goes from 1 to 4 (exclusive of 5).

If you want to include 5, use 1..=5.


3๏ธโƒฃ For Loop (Array)

fn main() {
    let fruits = ["Apple", "Banana", "Cherry"];

    for fruit in fruits.iter() {
        println!("I love {}!", fruit);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

.iter() returns each item of the array.

You can loop over arrays, vectors, and collections in Rust.


*Step 5: Break, Continue, and Return
*

break: Ends a loop immediately.

continue: Skips the current iteration and moves to the next.

return: Exits a function and returns a value.

Example with Break and Continue

fn main() {
    for number in 1..10 {
        if number % 2 == 0 {
            continue; // Skip even numbers
        }

        if number == 7 {
            break; // Stop the loop at 7
        }

        println!("Odd number: {}", number);
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

continue skips even numbers.

break stops the loop as soon as it encounters 7.


Practice Challenges

Challenge 1: FizzBuzz
Write a program that prints numbers from 1 to 20. But:

For multiples of 3, print "Fizz" instead of the number.

For multiples of 5, print "Buzz".

For multiples of both 3 and 5, print "FizzBuzz".

fn main() {
    for number in 1..=20 {
        if number % 3 == 0 && number % 5 == 0 {
            println!("FizzBuzz");
       #Copy and Complete the Code

}
Enter fullscreen mode Exit fullscreen mode

Challenge 2: Guess the Number (Simple Version)
Ask the user to guess a number between 10 and 20. If they guess correctly, print โ€œYou guessed it!โ€.

The code below is an example do yours to reflect 10 to 20 with a number in-between as the secret_number

use std::io;

fn main() {
    let secret_number = 7; // Hardcoded for simplicity
    println!("Guess a number between 1 and 10:");

    let mut guess = String::new();
    io::stdin().read_line(&mut guess).expect("Failed to read input");

    let guess: i32 = guess.trim().parse().expect("Please type a number!");

    if guess == secret_number {
        println!("You guessed it!");
    } else {
        println!("Wrong guess. The correct number was {}", secret_number);
    }
}

Enter fullscreen mode Exit fullscreen mode

๐ŸŽ‰ Congratulations on completing Rust Basics 3!
You now understand control flow, conditional statements, and loops. Youโ€™re becoming a Rustacean! ๐Ÿฆ€

Next, weโ€™ll explore functions, ownership, and borrowing in Rust Basics 4.


Did you try the challenges?
Post your solutions in the comments. If you have any questions, Iโ€™ll be happy to help! ๐Ÿฆ€

Check out Rust Documentation to learn more.

Top comments (0)