Answer:
Following are the program to the given question:
#include <stdio.h>//header file
double square_root(double N, double initialGuess)//defining a method square_root that takes two variable in parameters
{
double NG, LG = initialGuess,diff;//defining double variable
while(1)//use loop to calculate square root value
{
NG = 0.5 * (LG + N / LG);//using given formula
diff = NG - LG;//calculating difference
if(diff < 0)//use if to check difference is less than 0
diff = -diff;//decreaing difference
if(diff < 0.005)//use if that check difference is less than 0.005
break;//using break keyword
else//defining else block
{
LG = NG;//holding value
}
}
return NG;//return value
}
int main()//defining main method
{
double ans, n,initialguess = 1.0;//defining double variable
n = 4;//use n to hold value
ans = square_root(n, initialguess);//calculating the square root value and print its value
printf("square_root(%lf) = %lf \n", n, ans);//print calculated value with number
n = 120.5;//use n to hold value
ans = square_root(n, initialguess);//calculating the square root value and print its value
printf("square_root(%lf) = %lf \n", n, ans);//print calculated value with number
n = 36.01;//use n to hold value
ans = square_root(n, initialguess);//calculating the square root value and print its value
printf("square_root(%lf) = %lf \n", n, ans);//print calculated value with number
n = 0.25;//use n to hold value
ans = square_root(n, initialguess);//calculating the square root value and print its value
printf("square_root(%lf) = %lf \n", n, ans);//print calculated value with number
printf("\nEnter a number: ");//print message
scanf("%lf", &n);//input value
ans = square_root(n, initialguess);//calculating the square root value and print its value
printf("square_root(%lf) = %lf \n", n, ans);//print calculated value with number
}
Output:
Please find the attachment file.
Explanation:
- In this code, a method "square_root" is declared that takes two variable "N, initialGuess" in its parameters, inside the method a three double variable is declared.
- It uses the given formula and uses the diff variable to hold its value and uses two if to check its value is less than 0 and 0.005 and return its calculated value.
- In the main method, three double variables are declared that use the "n" to hold value and "ans" to call the method that holds its value and print its value.