Session Ready
Exercise

Sum of double vector

Since loops typically run much faster in C++ than in R, writing loops is an important skill. Let's start with a function that sums values from a NumericVector. This revisits the skills you learned in Chapter 2 Exercise 10, and the previous exercise in this chapter.

Instructions
100 XP
  • Complete the definition of a function, sum_cpp, that loops over elements of a NumericVector and return its sum.
    • Set n to be the size() of x.
    • Initialize result to zero.
    • Specify the for loop arguments. Initialize i to 0, set the iteration condition as i less than n, and increment i by one on each step.
    • In each iteration, add the ith element of x to result.