Breaking out of a for loop
Sometimes you may wish to exit a loop before you've completed all the iterations. For example, your code may succeed in its task before all possibilities have been tried. The break
keyword can be used to break out of a loop early.
The code pattern looks like this:
for(int i = 0; i < n; i++) {
// Do something
// Test for exiting early
if(breakout_condition) break;
// Otherwise carry on as usual
}
Here you'll rework the previous example so that the loop stops when the value does not change too much (based on a threshold). The function has been modified so that it returns a List
(you will learn about List
s in the next chapter), enabling you to see the approximation at each iteration.
This modified sqrt_approx()
function returns both the square root and the number of iterations it took to achieve this result based on the threshold.
This exercise is part of the course
Optimizing R Code with Rcpp
Exercise instructions
Add a break condition that triggers if the solution is good enough (based on the variable is_good_enough
).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
#include
using namespace Rcpp;
// [[Rcpp::export]]
List sqrt_approx(double value, int n, double threshold) {
double x = 1.0;
double previous = x;
bool is_good_enough = false;
int i;
for(i = 0; i < n; i++) {
previous = x;
x = (x + value / x) / 2.0;
is_good_enough = fabs(previous - x) < threshold;
// If the solution is good enough, then "break"
___(___) ___;
}
return List::create(_["i"] = i , _["x"] = x);
}
/*** R
sqrt_approx(2, 1000, 0.1)
*/