Hello

I have 4 problems to solve out of 4 I solved 3 but problem mention below is painfull, I am not able to find how I will interchange the '+' '-' operator. I need some code. I am using Turbo C++

Write a C++ function having two value parameters X and M with result type float to find sum of series given:
1-X+1/2!X2 – 1/3!X3+1/4!X4+…..+ 1/M!XM

Thank you.

## All 7 Replies

Raise the number -1 to a power, say n what will the outcome be when n is even? What if n is uneven? This tip should help.

One way might be to use the % (mod) operator in the loop (function Calculate returns the result of the calculation 1/M!XM

``````int M = 5; // some value
int Result = 1 - X;
for(int i = 1; i <= M; i++)
{
if( (i%2) == 0)
Result += Calculate(i);
else
Result -= Calculate(i);
}
``````

@Ancient Dragon
I tried your piece of code in my program.

Can you take a little botheration to check my code and verify it whether it is Correct or not

@ddanbe
I tried your piece of code in my program.

Can you take a little botheration to check my code and verify it whether it is Correct or not

Willing to do so, but where is your code?

commented: Thnakyou Code is posted +2

@ddanbe
Sorry I am missed to give the code
here it is

``````#include<iostream.h>
#include<conio.h>
#include<math.h>
float Calculate(int,int);
void main()
{
float X;
int M;
clrscr();
cout<<"Enter the limit of series: ";
cin>>M;
cout<<"Enter value for X: ";
cin>>X;
float Result = 1 - X;
for(int i = 1; i <= M; i++)
{
if( (i%2) == 0)
Result +=Calculate(i,X);
else
Result -=Calculate(i,X);
}
cout<<"Sum "<<Result;
getch();
}
float Calculate(int i,int X)
{
float s,power;
double fact=1.0;
for(int j=1;j<=i;++j)
{
fact*=j;
power=pow(X,i);
}
s=(float)1/fact*power;
return s;
}
``````

when you run your program does it produce correct results?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.