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 = 0declares the index to be an integer (the most common case), and sets the value to be0on the first iteration.i < nsets the iteration condition: onceireaches the valuen, this condition fails and the loop will stop running.i++means increase the value ofiby1on 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
Exercise instructions
- Initialize a local
doublex to one. - Specify a
forloop.- Initialize an integer,
i, to0. - Set the iteration condition as
iless thann. - Increment
iby one on each step.
- Initialize an integer,
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)
*/