The basic structure of the program is this:
1. issue an interactive prompt for the user to enter a non-negative number,
2. verify that the input is indeed non-negative, or that the user wishes to end the program,
3. calculate the square root of the input value, using the method to be described shortly,
4. print some information about how well the method worked,
5. go back to step 1.

Here is the square root method. Suppose the input value is in the variable a, type double. For convenience and to explain what’s going on, we’ll write the value a = b^2, but we don’t know the value of b yet (its value is sqrt(a) but we’re trying to calculate b ourselves). Start to compute a sequence of values xN by setting x0 = a. Once we know xn we can calculate xn+1 by the rule
xn+1 = ½ (xn + a/xn)
and then we just keep going until the sequence xN converges to b.

I have decided to use nested loops for the program but they aren't really working...

#include <iostream>
#include <cmath>   // Needed for rand operations.

int main ()
{
char quit='N';
while (toupper(quit) != 'Y')
{
cout <<"enter non zero number *****:"<<flush;
cin >> userInput;

If (userInput <=0)
{
cout <<"invalid. would you like to quit?(y/n):"<<flush;
cin>> quit;
}
x = a = userInput;
y= 0;

//sqrt
lasty= 0;
for(i=0;i<=15;i++)
{
y=0.5*(x+a/x);
x=y;
if (y == lasty)
break;
lasty=y;

I dont really understand what to do next to make this work....
Thanks

## All 2 Replies

I dont really understand what to do next to make this work....
Thanks

Flow chart. That's what you need.

x_{n+1} = \frac{1}{2}(x_{n}+\frac{a}{x_{n}})

Let's pretend you are trying to find the square root of 25. Thus in your formula above a would be 25. That never changes. x is the variable that gets updated.

a = 25
x = 100 // arbitary start value you can choose any number
//while condition
x = 0.5 * (x + ( a / x ))
end while
print x
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.