\[1+2+\dots+n\]

In the example below we have written a (faulty) function to compute the sum of the first n integer values using a for loop. However, the results when executiong this function are not as we expected. The reason for this error is the position of the initialisation of the sum variable (sum <- 0).

sum_of_first_n_numbers <- function(n) {
    for (i in 1:n) {
        sum <- 0
        sum <- sum + i
    }
    return(sum)
}

sum_of_first_n_numbers(1)
# 1
sum_of_first_n_numbers(2)
# 2
sum_of_first_n_numbers(3)
# 3
sum_of_first_n_numbers(600)
# 600

Exercise