# Developers Planet

teo93 February 2016

### Babylonian Algorithm with C++ unable to get loop to run

Is the refusal for the program to produce the result a consequence of it unable to get into the loop?

``````#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
double x, squareroot, oldsquareroot, counter=0;
cout << "Enter a positive number: " ;
cin >> x ;
{
for (oldsquareroot = x/2; abs(squareroot-oldsquareroot) >= 1e-9 &&   abs(squareroot - oldsquareroot)>=(1E-8*x);counter++ )
{
squareroot = (squareroot+x/squareroot)/2;
}

}
cout << setprecision(15);
cout << "The value of the squareroot is:" << squareroot << endl;
cout << "The number of interations required for the computation is:" <<  counter << endl;
return 0;

}
``````

ErmIg February 2016

There were some mistakes. Now it works fine.

``````#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main()
{
double x, squareroot, oldsquareroot, counter = 0;
cout << "Enter a positive number: ";
cin >> x;
{
squareroot = x; // fixed error 1: using of uninitialized variable.
for (oldsquareroot = x / 2; abs(squareroot - oldsquareroot) >=  1e-9 && abs(squareroot - oldsquareroot) >= (1E-8*x); counter++)
{
oldsquareroot = squareroot;// fixed eror 2: oldsquareroot is not changed in the loop and can't exit.
squareroot = (squareroot + x / squareroot) / 2;
}
}
cout << setprecision(15);
cout << "The value of the squareroot is:" << squareroot << endl;
cout << "The number of interations required for the computation is:" << counter << endl;
return 0;
}
``````