Please use C program gcc and post screen photo of your code to see it. Problem 2
ID: 3585549 • Letter: P
Question
Please use C program gcc and post screen photo of your code to see it.
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>
#include<stdlib.h>
int main(){
int m;
double n,in,tol;
double sq;
int i;
double diff;
printf("Enter positive number, initial guess,tolerance, max number of iterations :");
scanf("%lf %lf %lf %d",&n,&in,&tol,&m);
double *data = (double *)malloc(sizeof(double)*m);
diff = 100;
data[0] = in;
for (i = 1; i<m ; i++){
data[i] = 0.5*(data[i-1] + n/data[i-1]) ;
diff = data[i] - data[i-1];
if (diff < 0)
diff = -1 * diff;
if (diff <= tol){
break;
}
}
if (i==m){
printf("Max iterations %d reached, |x_{n+1} - x_n| = %.le ",i,diff);
}
printf("sqrt(%g): %.13e, number of iterations %d :",n,data[i-1],i);
return 0;
}