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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
#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:
1 2 3 4 5 |
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 . . . |