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

Hello my c-code below is not working correctly. When ran it does not use 0.0001

ID: 3716303 • Letter: H

Question

Hello my c-code below is not working correctly. When ran it does not use 0.0001 as n but 0 which is incorrect.What am I missing here?

#include <stdio.h>
#include <math.h>
double f(double x);
double simpsons(int n, double a, double b);
int main()
{
printf("For the integral f(x)dx with bounds of integration 0 to 9, ");
printf(" Integration by Simpson's Rule yields the following results: ");
double x0 = 0, xn = 9;
int n1 = 0.0001;
printf("For n = %d, the integral is %f ", n1, simpsons(n1, x0, xn));

return 0;
}
double f(double x)
{
double y;
if (x<3 && x>=0)
y=5*x;
if (x<6 && x>=3)
y=2.5*x;
if (x <= 9 && x >= 6)
y=-3*x;
return y;
}
/* Integration using Simpson's Rule */
double simpsons(int n, double a, double b)
{
int i;
double dx, x, sum;
dx = (b -a) / n;
sum = f(a) + f(b);
for (i = 1; i < n; i++) {
x = a + dx * i;
sum += 2 * (1 + i%2) * f(x);
}
sum *= dx/3;
return sum;
}

Explanation / Answer

Use this code. You are supposed to declare it as a double variable and I have changed the format specifier as well. The changes are in bold.

#include <stdio.h>
#include <math.h>
double f(double x);
double simpsons(int n, double a, double b);
int main()
{
printf("For the integral f(x)dx with bounds of integration 0 to 9, ");
printf(" Integration by Simpson's Rule yields the following results: ");
double x0 = 0, xn = 9;
float n1 = 0.0001;
printf("For n = %.4f, the integral is %f ", n1, simpsons(n1, x0, xn));

return 0;
}
double f(double x)
{
double y;
if (x<3 && x>=0)
y=5*x;
if (x<6 && x>=3)
y=2.5*x;
if (x <= 9 && x >= 6)
y=-3*x;
return y;
}
/* Integration using Simpson's Rule */
double simpsons(int n, double a, double b)
{
int i;
double dx, x, sum;
dx = (b -a) / n;
sum = f(a) + f(b);
for (i = 1; i < n; i++) {
x = a + dx * i;
sum += 2 * (1 + i%2) * f(x);
}
sum *= dx/3;
return sum;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote