0

In a square root function (in C) like this one:

double squareRoot(double n) {
   double i, precision = 0.00001;

   for(i = 1; i*i <=n; ++i);   //Integer part

   for(--i; i*i < n; i += precision);  //Fractional part

   return i;
}

what does this --i part(on line 4) do?

It works fine and for input 24, it gives 4.898980. But when this --i is replaced with just i, the result is 5.000000. Also, when i-- is used, it gives 4.898980 again. So, does that mean --i = i--? What's happening under the hood?

Also, I don't get the logic why just an i wouldn't suffice here as we're already done with the integer part. I'm a novice. Help please?

N Nair
  • 59
  • 1
  • 1
  • 6
  • 2
    The meaning of `--i` and `i--` can be found in any basic text book or using a search on the web. – R Sahu Oct 03 '16 at 20:43
  • After a sequence point (which is the `;` right after the `--i`) the `i` will have the same value for both `i--` and `--i`. – Eugene Sh. Oct 03 '16 at 20:43
  • It does the same thing in that function as it would do anywhere else. It's a pre-decrement operation. – Ken White Oct 03 '16 at 20:43
  • Because after the first loop `i` was `1` out of range. So the second loop decrements it, to be in range so it can step through in much smaller increments. – Weather Vane Oct 03 '16 at 20:43

1 Answers1

2

It's a 'step back', e.g. if you're doing sqrt(50) (7.07....)

for(i = 1; i*i <=n; ++i);   //Integer part

then i will finish at 8. But that's obviously PAST where the sqrt value actually is. so

for(--i; i*i < n; i += precision);  //Fractional part

will move back one step, and effectively run as

for(i=7; i*i < n; i += precision);  //Fractional part

and slowly work its way up to as close to 7.07.... as the precision will allow.

Marc B
  • 356,200
  • 43
  • 426
  • 500