w3resource

Rust Function: Find Sum of array elements

Rust Functions and Control Flow: Exercise-9 with Solution

Write a Rust function to find the sum of all elements in an array.

Sample Solution:

Rust Code:

// Define a function named 'sum_of_array' that takes an array of integers as input and returns the sum of all elements
fn sum_of_array(arr: &[i32]) -> i32 {
    // Initialize a variable 'sum' to store the sum of elements
    let mut sum = 0;

    // Iterate over each element of the array and add it to 'sum'
    for &num in arr {
        sum += num;
    }

    sum // Return the sum
}

fn main() {
    let array = [1, 2, 3, 4, 5]; // Define an array of integers

    // Call the 'sum_of_array' function with the array and store the result
    let result = sum_of_array(&array);

    // Print the sum of all elements in the array
    println!("Sum of all elements in the array: {}", result);
}

Output:

Sum of all elements in the array: 15

Explanation:

Here's a brief explanation of the above Rust code:

  • fn sum_of_array(arr: &[i32]) -> i32 { ... }: This is a function named "sum_of_array()" that takes an array slice 'arr' of integers (&[i32]) as input and returns the sum of all elements as an integer (i32).
  • Inside the function:
    • We initialize a variable 'sum' to store the sum of elements.
    • We iterate over each element 'num' of the array slice 'arr' using a "for" loop, adding each element to 'sum'.
  • Finally, we return the value of 'sum'.
  • In the main function,
    • Define an array named 'array' containing some integers.
    • Call the "sum_of_array()" function with a reference to the array ('&array') and store the result in a variable named 'result'.
    • Finally we print the sum of all elements in the array.

Rust Code Editor:

Previous: Rust Program: Print Fibonacci Sequence up to Specified Terms.
Next: Rust Function: Determine Palindrome.

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.