find the average of all elements in an array in rust

One way to find the average of all elements in an array in Rust is to loop through the array and calculate the sum of all elements. Then divide the sum by the length of the array to get the average. Here's the code:

main.rs
fn main() {
    let arr = [1, 2, 3, 4, 5];
    let mut sum = 0;

    for i in 0..arr.len() {
        sum += arr[i];
    }

    let average = sum as f32 / arr.len() as f32;

    println!("The average is {}", average);
}
219 chars
13 lines

In this example, we have an array of integers with five elements. We initialize a variable sum to zero and then loop through the array using a standard for loop. Inside the loop, we add the current element to the sum variable.

After the loop, we calculate the average by dividing the sum by the length of the array. We use as f32 to convert the sum and length to floating-point numbers because otherwise the division would result in integer division, which would discard the fractional part.

Finally, we print the result using println!().

related categories

gistlibby LogSnag