Rust Function: Check even or odd
Rust Pattern Maching: Exercise-1 with Solution
Write a Rust function that takes an integer and returns "even" if the integer is even and "odd" if it's odd.
Sample Solution:
Rust Code:
// Define a function named `even_or_odd` that takes an integer `num` as input and returns a static string slice.
fn even_or_odd(num: i32) -> &'static str {
// Check if the remainder of `num` divided by 2 is equal to 0.
if num % 2 == 0 {
// If the remainder is 0, return "even".
"even"
} else {
// If the remainder is not 0, return "odd".
"odd"
}
}
fn main() {
// Print the result of calling `even_or_odd` function with 7 as input.
println!("{}", even_or_odd(7)); // Output: odd
// Print the result of calling `even_or_odd` function with 22 as input.
println!("{}", even_or_odd(22)); // Output: even
}
Output:
odd even
Explanation:
In the exercise above,
- The function "even_or_odd()" takes an integer 'num 'as input.
- Inside the function, it checks if the remainder of dividing 'num' by 2 is equal to 0. If it is, the function returns "even", indicating that the number is even.
- If the remainder is not equal to 0, the function returns "odd", indicating that the number is odd.
- In the "main()" function, examples of calling "even_or_odd()" are provided with different integers to demonstrate its usage.
Rust Code Editor:
Previous: Rust Pattern Matching Exercises.
Next: Rust Function: Check vowel or consonant.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/functional-programming/rust-pattern-matching-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics