#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int n, lowerNum, uperNum,s1 = 2,s = 1,w = 0,w1 = 1,w2 = 3,st = 1,st1 = 3;
float x[30], y[30], temp = 0,temp1 = 0,temp2 = 0;
cout<<"\nNUMERICAL INTEGRATION\n\nEvaluate: Function to be integrated: x^2 dx\n";
cout<<"\nEnter value of x0: ";cin>>lowerNum;
cout<<"\nEnter value of xn: ";cin>>uperNum;
cout<<"\nEnter number of iteration: ";cin>>n;
cout<<"\nNumber of Iteration is "<<n<<endl;
float h = ((uperNum - lowerNum)/(float)n);
cout<<"\nWe have,\nn = "<<n<<"\nh = ("<<uperNum<<" - "<<lowerNum<<")/"<<n<<endl;
cout<<"\nthen,\nValue of h = "<<h<<endl<<"Value of n = "<<n<<endl<<endl;
x[0] = y[0] = lowerNum;
for(int i=1;i<=n;i++)
{
x[i] = x[0] + (i*h);
y[i] = x[i] * x[i];
}
for(int i=0;i<=n;i++)
{
cout<<"x["<<i<<"] = "<<x[i]<<",\ty["<<i<<"] = "<<y[i]<<endl;
}
cout<<"\nChoose the Rules to Calculate Answer:\n";
while(1)
{
int choice;
cout<<"\n1.Trapezoidal Rule\t2.Simpson's 1/3rd Rule\n3.Simpson's 3/8th Rule\t4.Weddles Rule\n5.EXIT\n-->";
cin>>choice;
switch(choice)
{
case 1:
float trapAns,num[5];
for(int i=0;i<n;i++)
temp = temp + y[i];
num[0] = (h/(float)2);
num[1] = y[0] + y[n];
num[2] = 2*temp;
num[3] = num[1] + num[2];
trapAns = num[0] * num[3];
cout<<"\nAnswer by Using Trapezoidal Rule = "<<trapAns<<endl;
temp = temp1 = 0;
break;
case 2:
float simOneThird, s1num[5];
while(s<n){
temp = temp + y[s];
s += 2;
}
while(s1<n){
temp1 = temp1 + y[s1];
s1 += 2;
}
s1num[0] = (h/(float)3);
s1num[1] = y[0] + y[n];
s1num[2] = 4 * temp;
s1num[3] = 2 * temp1;
s1num[4] = s1num[1] + s1num[2] + s1num[3];
simOneThird = num[0] * s1num[4];
cout<<"\nAnswer by Using Simpson's 1/3rd Rule = "<<simOneThird<<endl;
temp = temp1 = 0;
break;
case 3:
float simThreeEight, s3num[5];
//st = 1
while(st<n){
if((st/3)!=0)
temp = temp + y[st];
st++;
}
//st1 = 3
while(st1<n){
temp1 = temp1 + y[st1];
st1 += 3;
}
h = h*0.37;
s3num[1] = y[1] + y[n];
s3num[2] = 3*temp;
s3num[3] = 2*temp1;
s3num[4] = s3num[1] + s3num[2] + s3num[3];
simThreeEight = h * s3num[4];
cout<<"\nAnswer by Using Simpson's 3/8th Rule = "<<simThreeEight<<endl;
temp = temp1 = 0;
break;
case 4:
float weddles, wnum[5];
//w = 0
while(w<=n){
temp = temp + y[w];
w += 2;
}
//w1 = 1
while(w1<=n){
temp1 = temp1 + (5*y[w1]);
w1 += 4;
}
//w2 = 3
while(w2<=n){
temp2 = temp2 + (6*y[w2]);
w2 += 4;
}
wnum[0] = temp + temp1 + temp2;
wnum[1] = h * 0.3;
weddles = wnum[1]*wnum[0];
cout<<"\nAnswer by Using Weddle's Rule = "<<weddles<<endl;
temp = temp1 = temp2 = 0;
break;
case 5:
exit(0);
default:
cout<<"Please enter the option(1 - 5)";
}
}
}