First of ALL my C++ Version: Borland C++ 3.0
So, the question is to make a code for the following:

1 + x/1! + x3/2! + x5/3! ..............

I've made the following code, where b or n is Number of terms, and x or a is the in putted value of x. I am not able to figure out how to make the code for denominator i.e. how do I make 1!, 2!, 3! etc appear under denominator.
 ``1234567891011121314151617181920212223`` ``````#include #include #include void SUMFUN(int x,int n) { double sum=1; for(int i=1,j=1;i<=n,j<=n;i++,j+=2) { sum = sum + pow(x,j); } cout<<"\nSum: "<>a; cout<<"\nEnter Value of B: "; cin>>b; SUMFUN(a,b); getch(); }``````

Any help will be appreciated.... :D
Last edited on
I'd store the denominators in an array, calculate them in a separate loop. Something like:

 ``12345678910`` ``````int n = 3; int denominators[3] = {}; int sum = 1; for (int i=1;i<=n;i++) { sum = sum*i; denominators[i-1] = sum; }``````

denominators then will contain your denominators.

EDIT: And then use those values as the denominators in the loop you already have.
Last edited on
Can't Understand
So you got the formula, and as far as I can see you also got a loop which calculates 1 + x + x3 + x 5 and so on. What you need is therefore some way to calculate 1!, 2!, 3! and so on. This is exactly what the for loop I posted does.

Then you take your loop and modify it:

 ``1234`` ``````for(int i=1,j=1;i<=n,j<=n;i++,j+=2) { sum = sum + pow(x,j)/demonimators[i-1]; }``````

So you calculate the denominators before you execute the modified version of the loop you already have and store them in denominators. Then you can use the modified loop above.
The way I would recommend approaching this is to avoid the use of the math header and definitely avoid functions such as pow(). There are usually much simpler and more efficient ways.

In this case, in function SUMFUN(), declare two variables at the start:
 ``12`` `````` double numerator = 1.0; double denominator = 1.0;``````

Then on each iteration of the for loop, simply multiply each of these by a suitable factor, probably something like this (but I haven't checked, so please take care in case I missed something:
 ``123`` `````` numerator *= x; denominator *= i; sum += numerator/denominator;``````

(actually I think I gave you the values for calculating ex which isn't quite the same as the series you have).
Topic archived. No new replies allowed.