Common Array Operations
Part of the Fundamentals section of Coddy's Rust journey — lesson 68 of 75.
Here are some common array operations:
- Find the sum of all elements in an array:
let numbers = [1, 2, 3, 4, 5];
let mut sum = 0;
for number in &numbers {
sum += number;
}
println!("Sum: {}", sum);- Find the average of elements in an array:
let numbers = [1, 2, 3, 4, 5];
let mut sum = 0;
for number in &numbers {
sum += number;
}
let average = sum as f64 / numbers.len() as f64;
println!("Average: {}", average);- Find the maximum element in an array:
let numbers = [1, 5, 2, 9, 3];
let mut max = numbers[0];
for &number in &numbers[1..] {
if number > max {
max = number;
}
}
println!("Max: {}", max);- Find the minimum element in an array:
let numbers = [1, 5, 2, 9, 3];
let mut min = numbers[0];
for &number in &numbers[1..] {
if number < min {
min = number;
}
}
println!("Min: {}", min);Challenge
EasyCreate a function named calculate_stats that takes an array of integers of length 8 as input and performs the following operations:
- Calculates the sum of all elements in the array.
- Calculates the average of the elements in the array.
- Finds the maximum element in the array.
- Finds the minimum element in the array.
The function should return an array of doubles containing the sum, average, maximum, and minimum, in that order.
Try it yourself
use std::io;
use std::convert::TryInto;
fn calculate_stats(arr: [i32; 8]) -> [f64; 4] {
// Write your code here
}
fn main() {
let mut input_str_arr = String::new();
io::stdin().read_line(&mut input_str_arr).unwrap();
let numbers: [i32; 8] = input_str_arr.split(',').map(|s| s.parse::<i32>().unwrap()).collect::<Vec<i32>>().try_into().unwrap();
let stats = calculate_stats(numbers);
println!("Sum: {}", stats[0]);
println!("Average: {}", stats[1]);
println!("Maximum: {}", stats[2]);
println!("Minimum: {}", stats[3]);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input