w3resource

Rust Program: Even or Odd number checker

Rust Basic: Exercise-6 with Solution

Write a Rust program that checks if a number is even or odd and prints the result.

Sample Solution:

Rust Code:

fn main() {
    // Prompt the user to enter a number
    println!("Enter a number:");

    // Create a mutable string variable to store user input
    let mut input = String::new();

    // Read the user input from the standard input (keyboard)
    std::io::stdin().read_line(&mut input).expect("Failed to read input.");

    // Convert the user input to an integer
    let number: i32 = input.trim().parse().expect("Please enter a valid number.");

    // Check if the number is even or odd
    if number % 2 == 0 {
        // If the number is even, print a message indicating it
        println!("The number {} is even.", number);
    } else {
        // If the number is odd, print a message indicating it
        println!("The number {} is odd.", number);
    }
}

Output:

Enter a number:
The number 22 is even.
Enter a number:
The number 19 is odd.

Explanation:

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

  • fn main() { ... }: This is the entry point of the program, where execution begins.
  • println!("Enter a number:");: This line prints the prompt message using the "println!" macro.
  • let mut input = String::new();: This line declares a mutable string variable named input to store the user input.
  • std::io::stdin().read_line(&mut input).expect("Failed to read input.");: This line reads the user input from the standard input (keyboard) and stores it in the 'input' variable. The expect() method handles errors during input reading.
  • let number: i32 = input.trim().parse().expect("Please enter a valid number.");: This line converts the user input (which is a string) to an integer (i32). It uses the "trim()" method to remove leading and trailing whitespace from the input string, "parse()" to convert the trimmed string to an integer, and "expect()" to handle any errors during parsing.
  • if number % 2 == 0 { ... } else { ... }: This line checks if the number is even or odd using the modulo operator (%). If the remainder of dividing the number by 2 is zero, it means the number is even; otherwise, it's odd.
  • println! Using the println, this line prints a message that the number is even!
  • println!("The number {} is odd.", number);: This line prints a message indicating that the number is odd using the println! macro.

Rust Code Editor:

Previous: Rust Math Operations: Addition, Subtraction, Multiplication, Division.
Next: Rust Program: Counting from 1 to 10.

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.