ℹ️ 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

R

Goal -- WPM

Ready
Exercise Algorithm Area
1sum_vector_elements <- function(numbers) {
2# Check if the input vector is empty
3if (length(numbers) == 0) {
4return(0)
5}
6
7total_sum <- 0
8# Iterate through each element and add to the sum
9for (i in 1:length(numbers)) {
10total_sum <- total_sum + numbers[i]
11}
12
13return(total_sum)
14}
15
16# Example usage:
17# my_vector <- c(1, 2, 3, 4, 5)
18# result <- sum_vector_elements(my_vector)
19# print(result)
20
21# Edge case: empty vector
22# empty_vector <- numeric(0)
23# result_empty <- sum_vector_elements(empty_vector)
24# print(result_empty)
Algorithm description viewbox

Sum of Array Elements

Algorithm description:

This R function computes the sum of all numeric elements within a given vector. It iterates through each number in the vector and accumulates their total. This is a fundamental operation used in statistical analysis, data aggregation, and basic arithmetic operations on datasets. It provides a simple yet essential building block for more complex calculations.

Algorithm explanation:

The `sum_vector_elements` function calculates the sum of elements in a numeric vector. It initializes a variable `total_sum` to 0. Then, it iterates through the input vector `numbers` using a `for` loop, from the first element to the last. In each iteration, the current element `numbers[i]` is added to `total_sum`. After the loop finishes, `total_sum` holds the sum of all elements. The function includes an edge case check for an empty vector; if the vector is empty, it immediately returns 0, preventing errors. The time complexity is O(n), where n is the number of elements in the vector, because each element is visited exactly once. The space complexity is O(1) as it only uses a constant amount of extra space for the `total_sum` variable and loop counter.

Pseudocode:

function sum_vector_elements(numbers):
  if length(numbers) is 0:
    return 0

  total_sum = 0
  for i from 1 to length(numbers):
    total_sum = total_sum + numbers[i]

  return total_sum