please use C program gcc and be sure about your answer. Problem 2 (4 points) ite
ID: 3585645 • Letter: P
Question
please use C program gcc and be sure about your answer.
Problem 2 (4 points) iteration The square root of a number a > 0 can be computed using Newton's Zn+1 = 0.5(Zn + a/Zn), where zo is an initial guess Write a C program that takes as input an initial guess ro, o tolerance tol, and number of iterations, n max and iterates the above scheme until convergence or nmax is reached. The iterations converge when n+1-l tol, your program should also output a message with the value of +nl, e.g Enter positive number, initial guess, tolerance, max number of iterations: 100 1 1e-14 5 Max iterations 5 reached, lx-{n+1) -x_al = 3.3e-02 sqrt (100) 1.0000052895643e+01, number of iterations 5 Note: I may have the number of iterations above off by one Here use "Max iterations %d reached, lx-{n+1) -x-nl %.1e " . = . Store your program in file al_newton.cExplanation / Answer
#include<stdio.h>
#include<math.h>
double findRoot(double a, double x0, double tol, int maxIter) {
double x = x0;
double xPrev;
int count = 0;
do {
xPrev = x;
x = 0.5 * (x + a/x);
count++;
}while ( count < maxIter && abs(xPrev - x) > tol);
printf("%d iterations took place.", count);
}
int main() {
double a;
double x0;
double tol;
int maxIter;
do {
printf("Enter a +ve number: ");
scanf("%lf",&a);
}while (a < 0);
printf("Enter x0: ");
scanf("%lf",&x0);
printf("Enter tolerance: ");
scanf("%lf",&tol);
printf("Enter maxIter: ");
scanf("%lf",&maxIter);
printf("Squared root possibility is %lf", findRoot(a, x0, tol, maxIter));
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.