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
sum_of_first_n_numbers
function by moving the initialisation of the sum variable (sum <- 0
) to another position/line in order to get the expected behaviour. Also try to explain the reason behind this faulty behaviour for yourself.