The process of finding square root of a number can be divided into two steps. One step is to find integer part and second one is for fraction part.
Algorithm
We derive an algorithm for finding square root here −
START
Step 1 → Define value n to find square root of
Step 2 → Define variable i and set it to 1 (For integer part)
Step 3 → Define variable p and set it to 0.00001 (For fraction part)
Step 4 → While i*i is less than n, increment i
Step 5 → Step 4 should produce the integer part so far
Step 6 → While i*i is less than n, add p to i
Step 7 → Now i has the square root value of n
STOP
Pseudocode
The pseudocode of this algorithm can be derived as follows −
procedure square_root( n )
SET precision TO 0.00001
FOR i = 1 TO i*i < n DO
i = i + 1
END FOR
FOR i = i - 1 TO i*i < n DO
i = i + precision
END FOR
DISPLAY i AS square root
end procedure
Implementation
Implementation of this algorithm is given below −
#include <stdio.h>
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;
}
int main() {
int n = 24;
printf("Square root of %d = %lf", n, squareRoot(n));
return 0;
}
Output
Output of the program should be −
Square root of 24 = 4.898980