Get startedGet started for free

Do it again: do-while loop

The repeat loop in R is called a do while loop in C++. Compared to a while loop, it moves the condition to the end of the loop, so that the loop contents are guaranteed to be run at least once. The syntax is as follows:

do {
  // Do something
} while(condition);

Notice the semicolon after the while condition.

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Initiate the loop with a do statement.
  • Specify the while condition, so the loop keeps iterating while the value of is_good_enough is false.

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, double threshold) {
    double x = 1.0;
    double previous = x;
    bool is_good_enough = false;
    
    // Initiate do while loop
    ___ {
        previous = x;
        x = (x + value / x) / 2.0;
        is_good_enough = fabs(x - previous) < threshold;
    // Specify while condition
    } ___
    
    return x;
}

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