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 be0
on the first iteration.i < n
sets the iteration condition: oncei
reaches the valuen
, this condition fails and the loop will stop running.i++
means increase the value ofi
by1
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
Exercise instructions
- Initialize a local
double
x to one. - Specify a
for
loop.- Initialize an integer,
i
, to0
. - Set the iteration condition as
i
less thann
. - Increment
i
by 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)
*/