OneBite.Dev - Coding blog in a bite size

Find The Average Of All Elements In An Array In Rust

Code snippet for how to Find The Average Of All Elements In An Array In Rust with sample and detail explanation

Dealing with arrays is a common task in any programming language. In this article, we will be talking about how to find the average of all elements in an array in the Rust programming language.

Code snippet to Find The Average Of All Elements In An Array In Rust

Let’s start with a short code snippet demonstrating how to accomplish this task:

fn main() {
    let numbers = [1, 2, 3, 4, 5];
    let sum: i32 = numbers.iter().sum();
    let count = numbers.len() as i32;
    let average = sum / count;
    println!("Average: {}", average);
}

Code Explanation for Finding The Average Of All Elements In An Array In Rust

In the given code snippet, we start by defining our array of integers — let numbers = [1, 2, 3, 4, 5];

Then we move to the summing step. Here we make use of the iter method to create an iterator over the elements of the numbers array. We then use the sum method on the iterator to sum the elements. The total sum is stored in the variable sum:

let sum: i32 = numbers.iter().sum();

Next, we calculate the count of elements in the array using the len() function. This length is a usize type object, but we need an i32 type object to divide correctly and obtain the average. Therefore, we typecast it as i32:

let count = numbers.len() as i32;

After getting the sum and count, we find out the average by dividing sum by count:

let average = sum / count;

Lastly, we print the average using println!:

println!("Average: {}", average);

The current program calculates the average of integer elements. If the array contains floating-point numbers, you should change the data type of the elements and count accordingly. You will need to ensure that count should be cast to f32 or f64 as required. Also, use floating-point division (/) to calculate the average correctly.

This is how the simple task of finding the average of all elements in an array can be accomplished in the Rust programming language.

rust