Rust Program: Filter Odd numbers
Write a Rust program that iterates over a range of numbers and filters out odd numbers.
Sample Solution:
Rust Code:
fn main() {
// Define the range of numbers from 1 to 10 (inclusive)
let range = 1..=20;
// Filter out even numbers using iterator adapters
let odd_numbers: Vec<i32> = range.filter(|&x| x % 2 != 0).collect();
// Print the filtered odd numbers
println!("Filtered odd numbers: {:?}", odd_numbers);
}
Output:
Filtered odd numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Explanation:
In the exercise above,
- let range = 1..=10;: This line defines a range from 1 to 10 (inclusive) using the ..= syntax, which includes both the start and end values.
- let odd_numbers: Vec<i32> = range.filter(|&x| x % 2 != 0).collect();: It filters the numbers in the range using the "filter" iterator adapter. The closure |&x| x % 2 != 0 is applied to each element of the range, returning 'true' for odd numbers (those with a remainder when divided by 2). The "collect()" method collects the filtered odd numbers into a vector.
- println!("Filtered odd numbers: {:?}", odd_numbers);: Finally, it prints the vector containing the filtered odd numbers.
Rust Code Editor:
Previous: Rust Program: Sum of Array elements.
Next: Rust Program: Convert strings to Uppercase.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics