#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{   clrscr();
int n,x,i,j;
float p,fact=1.0,sum=0.0;
cout<<"\n\tEnter the number: ";
cin>>n;
cout<<"\n\n\tEnter the Value of \'x\': ";
cin>>x;

for(i=1;i<=n;i++)
{   for(j=(2*j-1);j>0;j--)
{ fact=j*fact;
if(i%20==0)
p=(-1)*pow(x,(2*i-1));
else
p=pow(x,(2*i-1));
sum+=p/fact;
}
}
cout<<"\n\tThe sum is "<<sum;

getch();
}

One problem may be that you never initialized any of your variables.

//These could literally be any value.
int n,x,i,j;

Here you create a variable 'j', and make a whole bunch of loop conditions that are based on 'j'... 'j' could be anything......

for([B]j[/B]=(2*[B]j[/B]-1);[B]j[/B]>0;[B]j[/B]--)

Well here is the code(Not edited) in code tag.

/*x-(x^3/3!)+(x^5/5!)-(x^7/7!).......*/

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{	clrscr();
int n,x,i,j;
float p,fact=1.0,sum=0.0;
cout<<"\n\tEnter the number: ";
cin>>n;
cout<<"\n\n\tEnter the Value of \'x\': ";
cin>>x;

for(i=1;i<=n;i++)
{	for(j=(2*j-1);j>0;j--)
{ fact=j*fact;
if(i%20==0)
p=(-1)*pow(x,(2*i-1));
else
p=pow(x,(2*i-1));
sum+=p/fact;
}
}
cout<<"\n\tThe sum …

All 7 Replies

One problem may be that you never initialized any of your variables.

//These could literally be any value.
int n,x,i,j;

Here you create a variable 'j', and make a whole bunch of loop conditions that are based on 'j'... 'j' could be anything......

for([B]j[/B]=(2*[B]j[/B]-1);[B]j[/B]>0;[B]j[/B]--)

Captain Neo! Use the code tag.

Well here is the code(Not edited) in code tag.

/*x-(x^3/3!)+(x^5/5!)-(x^7/7!).......*/

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{	clrscr();
int n,x,i,j;
float p,fact=1.0,sum=0.0;
cout<<"\n\tEnter the number: ";
cin>>n;
cout<<"\n\n\tEnter the Value of \'x\': ";
cin>>x;

for(i=1;i<=n;i++)
{	for(j=(2*j-1);j>0;j--)
{ fact=j*fact;
if(i%20==0)
p=(-1)*pow(x,(2*i-1));
else
p=pow(x,(2*i-1));
sum+=p/fact;
}
}
cout<<"\n\tThe sum is "<<sum;

getch();
}
commented: Pos. rep to to get you back in the game. +15

To use only cout... you need to add the namespace.

using namespace std;

or

std::cout<<foo;

To use only cout... you need to add the namespace.

using namespace std;

or

std::cout<<foo;

I think he is using pretty much an old compiler, most probably Turbo C++ conio.h & clrscr() points to that. So i think he don't need to use namespace std, since it applies to modern compilers only.

Problem seems to be with the nested loop,

for(i=1;i<=n;i++)
{	for(j=(2*i-1);j>0;j--) //Changed j to i
fact=j*fact;
if(i%2==0) //changed 20 to 2.
p=(-1)*pow(x,(2*i-1));
else
p=pow(x,(2*i-1));
sum+=p/fact; //Deleted those braces

}

Now that should work.......

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.