Q: To find the sum of the following series:

 x - x2/2! + x4/4! - x8/8! + ...n terms


/* Sum of the following series:
 x - x^2/2! + x^4/4! -x^8/8!+.....n terms
*/


#include<iostream.h>
#include<math.h>
#include<conio.h>


//Recursive Function to find Factorial

int fact(int f)
{
if(f>1)
{ f*=fact(f-1); return f; }
else
return 1;
}

void main()
{

clrscr();

int x,n;

cout<<"To find the sum of the folowing series:"<<'\n';
cout<<" x - x^2/2! + x^4/4! - x^8/8!+.....n terms"<<'\n';

cout<<"\n Enter the value of x"<<"\n ";
cin>>x;
cout<<" Enter no of terms (n)"<<"\n ";
cin>>n;
cout<<"\n Sum=";

float num,den;
float sum=0.0;

//first term:
sum+=x;
cout<<x;

for(int i=1,j=2; i<=n-1; i++, j=pow(2,i))

 //n-1 because the first term is taken seperately already.

 //pow(2,n-1), as 2,4,8,16... are 2^1, 2^2, 2^3, 2^4...2^n-1.

{

num=pow(x,j);
den=fact(j);

if(i%2==0) //even
{
sum+=num/den;
cout<<"+";
}

else //odd
{
sum-=num/den;
cout<<"-";
}

cout<<" ("<<num<<"/"<<den<<")";

}

cout<<"\n The Sum of the series is: "<<sum;
getch();

}



 OUTPUT

To find the sum of the folowing series:

 x - x^2/2! + x^4/4! - x^8/8!+.....n terms
 Enter the value of x
 1
 Enter no of terms (n)
 4

 Sum=1- (1/2)+ (1/24)- (1/-25216)
 The Sum of the series is: 0.541706



 OUTPUT #2

To find the sum of the folowing series:
 x - x^2/2! + x^4/4! - x^8/8!+.....n terms

 Enter the value of x
 2
 Enter no of terms (n)
 3

 Sum=2- (4/2)+ (16/24)
 The Sum of the series is: 0.666667



Comments