w3resource

Rust Program: Sum of Array elements

Rust Iterators and Iterator Adapters: Exercise-8 with Solution

Write a Rust program that iterates over a vector of arrays [i32; 2] and calculates the sum of the first and second elements of each array.

Sample Solution:

Rust Code:

fn main() {
    // Define a vector of arrays [i32; 2]
    let arrays = vec![[1, 2], [3, 4], [5, 6]];

    // Initialize a variable to store the sum
    let mut sum = 0;

    // Iterate over each array in the vector
    for arr in &arrays {
        // Add the first and second elements of the current array to the sum
        sum += arr[0] + arr[1];
    }

    // Print the sum
    println!("Sum of first and second elements of each array: {}", sum);
}

Output:

Sum of first and second elements of each array: 21

Explanation:

The above Rust code iterates over a vector of arrays, where each array contains two integers. It calculates the sum of the first and second elements of each array by iterating over the vector and accessing the elements of each array using indexing (arr[0] and arr[1]). The sums are accumulated in the 'sum' variable. Finally, it prints the total sum of the first and second elements of all arrays in the vector.

Rust Code Editor:


Previous: Rust Program: Iterate over Option i32 values.
Next: Rust Program: Filter Odd numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.