ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Sum of Array Elements

Rust

Goal -- WPM

Ready
Exercise Algorithm Area
1fn sum_array(nums: &[i32]) -> i32 {
2let mut total = 0;
3for num in nums {
4total += num;
5}
6total
7}
8
9fn main() {
10let arr1 = [1, 2, 3, 4, 5];
11println!("Sum of {:?}: {}", arr1, sum_array(&arr1));
12
13let arr2 = [-1, 0, 1];
14println!("Sum of {:?}: {}", arr2, sum_array(&arr2));
15
16let arr3 = [];
17println!("Sum of {:?}: {}", arr3, sum_array(&arr3));
18
19let arr4 = [100];
20println!("Sum of {:?}: {}", arr4, sum_array(&arr4));
21}
Algorithm description viewbox

Sum of Array Elements

Algorithm description:

This Rust function `sum_array` computes the sum of all integer elements within a given array. It iterates through each number in the array and adds it to a running total. This is a fundamental operation for data analysis and numerical computations, often used as a building block for more complex algorithms.

Algorithm explanation:

The `sum_array` function initializes a mutable variable `total` to 0. It then iterates through each element `num` in the input slice `nums`. In each iteration, the current `num` is added to `total`. After the loop finishes, `total` holds the sum of all elements. If the input slice `nums` is empty, the loop will not execute, and the function will correctly return the initial value of `total`, which is 0. The time complexity is O(n), where n is the number of elements in the array, because each element is visited exactly once. The space complexity is O(1) as it only uses a single variable to store the sum.

Pseudocode:

function sum_array(nums):
  total = 0
  for each number num in nums:
    total = total + num
  return total