/*PROGRAM TO PRINT SUM OF THE FOLLOWING SERIES -
X + X*X/2! + X*X*X/3! + X*X*X*X/4!....n terms.
I'm not getting the correct output.
eg-for n=3 and x=2;
compiler's ans = 4.66
correct ans = 5.3.
HELP ME OUT...*/

``````#include<iostream.h>
#include<math.h>
#include<conio.h>
void main ()
{
clrscr();
float x,sum=0;
int n,fact=1,j,k;
cout<<"\nEnter For n";
cin>>n;
cout<<"\nEnter For X";
cin>>x;
for(int i=1;i<=n;++i)
{
j=i;
k=i;
{
while(j)
{
fact=fact*j;
--j;
}
}
sum+=pow(x,k)/fact;
}
cout<<"The Sum Of Series Is:"<<sum;
getch();
}``````

[CODE] cout << "fact = " << fact << endl;[/CODE]
right after line 24, and see what happens.

## All 7 Replies

first, to be more clearly, erase the '{' and '}' outside while cicle, and the variable k and j. you can change the while cicle for a for cicle beginning at 1 and ending at i+1 and doing fact=fact*j. you must modify too the first cicle for starting at 0. like this:

``````for(int i=0;i<n+1;i++)
{

for(int j=1;j<i+1;j++)
fact=fact*j;

sum+=pow(x,i)/fact;
}``````

the problem is only at the condition of the cicles

I'm not sure if you've got to recursions yet but I would advise creating a simple recursive function that calculates the prime of the denominator e.g

``float prime(float num);``

Then you could use your for loop like so:

``````for(int i=1;i<=n;++i)
{
sum += (pow(x,i)/prime(i));
}``````

:)

commented: Bad Suggestion... -4

1) Format your code
2) main() is not a void
3) Don't use conio.h because it's non-standard and only a couple compilers have it defined
4) The .h version of C++ headers have been replaced years ago

Al41007 is on the right track, but in his version, on the first pass through the “i” loop (that is when i=0), the “j” loop does not execute. This may be okay. I think it may help to more clearly describe the algorithm. It is actually the sum of (X*(X^n)/n! from 0 through n-1. (That is, a total of “n” iterations, starting at 0). Remember, the value of 0 factorial is 1. This can actually be done in a single “for” loop.

``cout << "fact = " << fact << endl;``

right after line 24, and see what happens.

Thank u all for ur support....i finally solved the problem....actually the factorial variable should be initialized inside the for loop...(intfact=1)and the answer is correct now..!!

``cout << "fact = " << fact << endl;``