Rust Program: Find maximum and minimum in array
Write a Rust program that implements two functions to find the maximum and minimum numbers in an array.
Sample Solution:
Rust Code:
fn find_max(numbers: &[i32]) -> Option<i32> {
// Return None if the array is empty
if numbers.is_empty() {
return None;
}
// Initialize max_num with the first element of the array
let mut max_num = numbers[0];
// Iterate over the array to find the maximum number
for &num in numbers {
if num > max_num {
max_num = num;
}
}
Some(max_num)
}
fn find_min(numbers: &[i32]) -> Option<i32> {
// Return None if the array is empty
if numbers.is_empty() {
return None;
}
// Initialize min_num with the first element of the array
let mut min_num = numbers[0];
// Iterate over the array to find the minimum number
for &num in numbers {
if num < min_num {
min_num = num;
}
}
Some(min_num)
}
fn main() {
let numbers = [3, 7, 2, 8, 1, 5]; // Define an array of numbers
// Call the find_max function to find the maximum number
match find_max(&numbers) {
Some(max) => println!("Maximum number: {}", max),
None => println!("The array is empty!"),
}
// Call the find_min function to find the minimum number
match find_min(&numbers) {
Some(min) => println!("Minimum number: {}", min),
None => println!("The array is empty!"),
}
}
Output:
Maximum number: 8 Minimum number: 1
Explanation:
Here's a brief explanation of the above Rust code:
- 'find_max' function: This function takes a slice of 'i32' numbers as input and returns an 'Option<i32>' representing the maximum number found in the array. If the array is empty, it returns 'None'. Otherwise, it iterates over the array to find the maximum number.
- 'find_min' function: This function takes a slice of 'i32' numbers as input and returns an 'Option<i32>' representing the minimum number found in the array. If the array is empty, it returns 'None'. Otherwise, it iterates over the array to find the minimum number.
- 'main' function: In the 'main' function, we define an array of numbers. We then call the 'find_max' function to find the maximum number and the 'find_min' function to find the minimum number in the array. Finally, we print the results.
Rust Code Editor:
Previous: Rust Function: Check Prime number.
Next: Rust Function: Calculate factorial of a number.
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