Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a C-Program that will take the square root of a number using a square-roo

ID: 3848586 • Letter: C

Question

Create a C-Program that will take the square root of a number using a square-root function that corresponse to the following protoype: double mySqrt(double x); (for x => 0)

Please use the Newton-Raphson equation:

Relative error:

-"Find the quare root of" Displays on the screen when ran. User enters a number and hits return, and then the application prints the quare root of the number enter, or an error message if the user enters a negative number.

- The function should check to make sure the number entered by the user is not negative. If the user enters a negative number and that negative number is given to the function mySqrt(x), mySqrt(x) should return -1 as an error code. The main program can check for the error code and decide what message to print to the user if the error code is returned.

- To calculate the relative error, you will need an absolute value function. You can write your own, or use the fabs( ) function from the #include library.

Thank you!

UPDATE:

k+1---

Explanation / Answer

#include<stdio.h>
#include<math.h>


double mySqrt(double a) {
   double xPrev; //this variable holds the previous value of x
   double x = a/2; // holds the current value of x
   if (a < 0) //checks if the input is -ve
       return -1;
   do {
       xPrev = x; //save present value to prev value
       x = 0.5 * (xPrev + (a / xPrev)); // update x accordingly
   } while(fabs((x - xPrev)/x) > 0.001); //continuation factor
   return x;
}


void main() {
   double n, result;
   printf("Find square root of: ");
   scanf("%lf", &n);
   result = mySqrt(n);
   if (result == -1) //check in main function
       printf("square roots of -ve numbers cannot be found. ");
   else
       printf("Square root of %lf is %lf", n, result);
      
}

I tried my best to keep the code assimple as possible. I hope you like the solution. You will also find comments to make things easy. Let me know if you have any trouble. I shall be glad to help you.