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

C++ Make sure that you initialize a sum variable each time the for-loop is execu

ID: 3539613 • Letter: C

Question

C++

Make sure that you initialize a sum variable each time the for-loop is executed (in other words, whenever you increase the value of n and begin a new estimate). You will want to update the sum by adding the area of each trapezoid when you calculate it. At the end of your for-loop, after you have added the area of the nth trapezoid, your sum will be contain the approximation of the integral. After exiting the for-loop, the do-while condition will compare the new error with the desired error you have set up in the condition statement, and this will determine whether the loop is repeated with a larger number of sub-intervals.   

Hints: Have the program display intermediate results so you can see what it is doing. You could report the value of n, the integral approximation, and the error for each trial. While the program is running, you should see n increasing and error decreasing until the solution converges. Make sure you use a cin statement or other suitable means after the final cout statement to freeze the display until the user is ready to close the dialogue box.

Explanation / Answer

#include<iostream>

#include<math.h>

#define PI 3.1415926


using namespace std;


double fnValue(double x) // value of function to be integrated

{

return 4.0/(1+ x*x);

}

int main()

{

int n=0;

double sum=0;

do{

n++;

sum=0; //initialising sum to 0

for (int i = 0; i < n; i++)

{

sum += ((fnValue(1.0*(i+1)/n)+fnValue(1.0*i/n))/2)*1.0/n; // adding area of one trapazoid to sum

}

printf("n = %d, integral approximation = %lf, error = %lf ",n,sum,fabs(sum-PI)); //printing intermediate values

}

while(fabs(sum-PI)>0.000001); //checking correctiness up to 6 decimal places

printf("Final Solution : %lf ",sum);

printf("Final n : %d ",n);

getchar(); //freezing the screen


}

please rate the answer

yes the higher the n , lesser will be the error since we taking area of trapazoid, so all must be straight lines.

higher n , means function between i/n and (i+1)/n, is almost straight line.

the function fnValue gives value of function and x.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote