In this post, I am going to write a very simple C program to find Square Root. I am using the Newton Raphson method to find the square root of a number.
#include <stdio.h>
#include <math.h>
// equivalent to 10^-7 -> accurate upto 7 decimal places
// can be set according to need or even taken in as input
const double MAX_ERROR = 1e-7;
// Function to return the Square Root value
double squareRoot(int x)
{
// initial guess for the root
double r = 1;
while (fabs(r*r - x) > MAX_ERROR)
{
// value of 'r' moves closer and closer to the actual root value
r = (r + x/r) / 2;
}
return r;
}
int main()
{
// get the number from user
int num;
printf("Enter a number to find the Sqaure root:");
scanf("%d", &num);
printf("%lf", squareRoot(num));
return 0;
}Sample output of this program:
Enter a number to find the Sqaure root:3 1.732051 -------------------------------- Process exited after 1.78 seconds with return value 0 Press any key to continue . . .