Session Ready
Exercise

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.)

Instructions
100 XP
  • 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.