Get startedGet started for free

Calculating square roots with a for loop

Just as in R, C++ for loops run the same code a specified number of times, only changing an index value on each iteration. The syntax for a for loop is slightly more complex than R though.

for(int i = 0, i < n, i++) {
  // Do something
}
  • int i = 0 declares the index to be an integer (the most common case), and sets the value to be 0 on the first iteration.
  • i < n sets the iteration condition: once i reaches the value n, this condition fails and the loop will stop running.
  • i++ means increase the value of i by 1 on each iteration.

Here you'll complete the definition of a function for calculating the square-root using the Babylonian method. (For real-world code, you should just use sqrt(), which uses a faster modern algorithm.)

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Initialize a local double x to one.
  • Specify a for loop.
    • Initialize an integer, i, to 0.
    • Set the iteration condition as i less than n.
    • Increment i by one on each step.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

#include 
using namespace Rcpp;

// [[Rcpp::export]]
double sqrt_approx(double value, int n) {
    // Initialize x to be one
    double x = ___;
    // Specify the for loop
    ___(int i = ___; ___; ___) {
        x = (x + value / x) / 2.0;
    }
    return x;
}

/*** R
sqrt_approx(2, 10)
*/
Edit and Run Code