1.Algorithm:

This method can be derived from (but predates) Newton – Raphson method.
1 Start with an arbitrary positive start value x (the closer to the
root, the better).
2 Initialize y = 1.
3. Do following until desired approximation is achieved.
a) Get the next approximation for root using average of x and y
b) Set y = n/x
2.Implementation:

[pastacode lang=”c” manual=”%2F*Returns%20the%20square%20root%20of%20n.%20Note%20that%20the%20function%20*%2F%0Afloat%20squareRoot(float%20n)%0A%7B%0A%20%20%2F*We%20are%20using%20n%20itself%20as%20initial%20approximation%0A%20%20%20This%20can%20definitely%20be%20improved%20*%2F%0A%20%20float%20x%20%3D%20n%3B%0A%20%20float%20y%20%3D%201%3B%0A%20%20float%20e%20%3D%200.000001%3B%20%2F*%20e%20decides%20the%20accuracy%20level*%2F%0A%20%20while(x%20-%20y%20%3E%20e)%0A%20%20%7B%0A%20%20%20%20x%20%3D%20(x%20%2B%20y)%2F2%3B%0A%20%20%20%20y%20%3D%20n%2Fx%3B%0A%20%20%7D%0A%20%20return%20x%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20function*%2F%0Aint%20main()%0A%7B%0A%20%20int%20n%20%3D%2050%3B%0A%20%20printf%20(%22Square%20root%20of%20%25d%20is%20%25f%22%2C%20n%2C%20squareRoot(n))%3B%0A%20%20getchar()%3B%0A%7D” message=”C” highlight=”” provider=”manual”/]

Example:

n = 4 /*n itself is used for initial approximation*/
Initialize x = 4, y = 1
Next Approximation x = (x + y)/2 (= 2.500000), 
y = n/x  (=1.600000)
Next Approximation x = 2.050000,
y = 1.951220
Next Approximation x = 2.000610,
y = 1.999390
Next Approximation x = 2.000000, 
y = 2.000000
Terminate as (x - y) > e now.

If we are sure that n is a perfect square, then we can use following method. The method can go in infinite loop for non-perfect-square numbers. For example, for 3 the below while loop will never terminate.

[pastacode lang=”c” manual=”%2F*Returns%20the%20square%20root%20of%20n.%20Note%20that%20the%20function%0A%20%20will%20not%20work%20for%20numbers%20which%20are%20not%20perfect%20squares*%2F%0Aunsigned%20int%20squareRoot(int%20n)%0A%7B%0A%20%20int%20x%20%3D%20n%3B%0A%20%20int%20y%20%3D%201%3B%0A%20%20while(x%20%3E%20y)%0A%20%20%7B%0A%20%20%20%20x%20%3D%20(x%20%2B%20y)%2F2%3B%0A%20%20%20%20y%20%3D%20n%2Fx%3B%0A%20%20%7D%0A%20%20return%20x%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20above%20function*%2F%0Aint%20main()%0A%7B%0A%20%20int%20n%20%3D%2049%3B%0A%20%20printf%20(%22%20root%20of%20%25d%20is%20%25d%22%2C%20n%2C%20squareRoot(n))%3B%0A%20%20getchar()%3B%0A%7D” message=”C program” highlight=”” provider=”manual”/] [ad type=”banner”]