w3resource

Rust Weather Condition Checker: Check and set Boolean variable for Sunny weather

Rust Variables and Data Types: Exercise-4 with Solution

Write a Rust program that declares a boolean variable is_sunny and sets it to true if it's sunny and false otherwise.

Sample Solution:

Rust Code:

fn main() {
    // Declare a boolean variable named 'is_sunny'
    let is_sunny: bool;

    // Simulate checking weather conditions
    let weather_condition = "sunny";

    // Check if the weather condition is sunny
    if weather_condition == "sunny" {
        is_sunny = true; // If it's sunny, set 'is_sunny' to true
    } else {
        is_sunny = false; // If it's not sunny, set 'is_sunny' to false
    }

    // Print the value of 'is_sunny' to indicate the current weather condition
    if is_sunny {
        println!("It's sunny today!");
    } else {
        println!("It's not sunny today.");
    }
}

Output:

It's sunny today!

Explanation:

Here's a brief explanation of the above Rust code:

  • 'fn main() { ... }': This is the program's entry point.
  • 'let is_sunny: bool;': This line declares a boolean variable named 'is_sunny' without initializing it. It will be initialized later based on weather conditions.
  • 'let weather_condition = "sunny";': This line simulates checking the weather condition. In this example, the weather condition is "sunny".
  • 'if weather_condition == "sunny" { ... } else { ... }': This conditional statement checks if the weather condition is sunny. If it is, the 'is_sunny' variable is set to 'true'; otherwise, it's set to 'false'.
  • 'if is_sunny { ... } else { ... }': This conditional statement prints a message based on the value of 'is_sunny'. If 'is_sunny' is 'true', it prints "It's sunny today!"; otherwise, it prints "It's not sunny today."

Rust Code Editor:

Previous: Rust: Increment counter by specified amount.
Next: Rust Program: Convert Celsius to Fahrenheit.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.