# Thread: How to write a given function

1. ## How to write a given function

please help me to write a function with two arguments double x and int n.the function should return a value of type double and it should perform sum of following series;

1-[(x)/1!]+[(x^2)/3!]-[(x^3)/5!]+[(x^4)/7!]....upto n terms

thank you

2. You could start by giving us what you have so far and maybe a more specific question. We're not going to do homework.

3. Code:
```#include <iostream>
#include<string.h>
#include<math.h>
using namespace std;
int factorial(int j)
{

if (j==1)
return 1;
else
return j*factorial(j-1);
}
double sumsequence(double x,int n){
int sign=+1;
double sum=0;

int term;
sum +=1;
for (int i =1;i<=n;i++)
{
sign *= -1;
term =  (sign * pow(x,i))/factorial(i);
sum+=term;

}
return sum;
}

int main(){
double a;
int b;

cin >> a>>b;
sumsequence(a,b);

}```

4. Cleaned up code: indented, removed unnecessary whitespace, replaced C headers with appropriate C++ headers, moved temporaries into loop instead of top of function:
Code:
```#include <iostream>
#include <cmath>
using namespace std;

int factorial(int j)
{
if (j == 1)
return 1;
else
return j * factorial(j - 1);
}

double sumsequence(double x, int n)
{
int sign = 1;
double sum = 1;

for (int i = 1; i <= n; i++)
{
sign *= -1;
int term = (sign * pow(x, i)) / factorial(i);
sum += term;
}
return sum;
}

int main()
{
double a;
int b;

cin >> a >> b;
sumsequence(a, b);
}```
Now, the problems are two-fold. First, note that (sign * pow(x, i)) / factorial(i) may not be an int! You are dividing by a number, so it may be a floating point, so you should make the temporary a double.
Secondly, the factorial(i). The formula says that the factorial shall be incremented by 2 on each iteration, but you only increment it by one.

5. still not working ....this is what i have now

Code:
```#include <iostream>
#include <cmath>
using namespace std;

int factorial(int j)
{
if (j == 1)
return 1;
else
return j * factorial(j - 1);
}

double sumsequence(double x, int n)
{
int sign = 1;
double sum = 1;
int k=1;

for (int i = 1; i <= n; i++)
{
sign *= -1;
double term = (sign * pow(x, i)) / factorial(k);
sum += term;
k+=2;
}
return sum;
}

int main()
{
double a;
int b;

cin >> a >> b;
sumsequence(a, b);
}```

6. You need to be more specific. What is not working? The code is giving correct results for a = 10, b = 2 and b = 3, according to my tests. Are you testing some other inputs?

7. it is just returning 0.here is the screenshot of output.

8. If you implying the "process returned 0," you can ignore that. That has nothing to do with the actual program. You aren't actually printing the result of your function, though. You're just throwing your calculation away.