Feb 24, 2012 at 2:46pm UTC
Write definition for a function SumSequence( ) in C++ with two
arguments/parameters — double x and int n. The function should return a value of
type double and it should perform sum of the following series : 4
1/x — 3!/x
2
+ 5!/x
3
— 7!/x
4
+ 9!/x
5
— ... up to n terms
(Note : The symbol ! represents Factorial of a number i.e.
5! = 5 × 4 × 3 × 2 × 1)
I tried to answer but nothing happens:
I wrote it like this please point out errors..
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ clrscr();
int n;
double x, sum=0;
int fact=1;
for(int i=1; i<n;i++)
{
for(int j=((2*i))-1;j>0;j--) //for factorial;
{
fact*=j;}
sum+=pow(-1,i)*( fact)/(pow(x,i);
fact=1;
}
cout<<"Sum is: ";
getch();
}
Last edited on Feb 24, 2012 at 2:56pm UTC
Feb 24, 2012 at 2:57pm UTC
Without running to code to check if it works the obvious error here is.
cout << "Sum is: ";
You forgot to put sum in there.
Some other points though. use int main() and return 0 at the end. iostream.h is depreciated and you should just need iostream now without the .h.
Edit: You haven't actually written a function though, your code should look like...
1 2 3 4 5 6 7 8 9 10 11 12 13
// includes here
double function_name(double x, int n)
{
// some code here.
return some_double;
}
int main()
{
cout << function_name(some_double, some_int);
return 0;
}
Right now x isn't initialized so your code won't work like you want it to.
Last edited on Feb 24, 2012 at 3:06pm UTC
Feb 24, 2012 at 3:04pm UTC
Oh damn I will check sorry.
Feb 24, 2012 at 3:06pm UTC
Now works I think.
#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{ clrscr();
int n;
double x, sum=0;
cout <<" Enter Value for x: ";
cin>>x;
cout<<" Enter valu for n: ";
cin>>n;
int fact=1;
for(int i=1; i<=n;i++)
{ for(int j=((2*i))-1;j>0;j--)
{fact*=j;
}
sum+=-pow(-1,i)*fact/(pow(x,i));
fact=1;
}
cout<<"Sum is: "<<sum;
getch();
}
Feb 24, 2012 at 3:08pm UTC
pow(-1,i) should be pow(-1,i+1)
but you still haven't really written a function. You have the right idea of how to solve it though so I'll just post my version to show you what I mean by a function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
double SumSequence(double x, int n)
{
double sum = 0;
for (int i = 1; i <= n; i++)
{
int fact = 1;
for (int j = 2*i - 1; j > 0; j--)
{
fact*=j;
}
sum+=pow(-1,i+1)*fact/pow(x,i);
fact=1;
}
return sum;
}
int main()
{
cout << SumSequence(11.0, 50) << endl;;
return 0;
}
The question asks you to write a function with a return type of a double which is what the above code does.
edit: also would be good to put in a check to make sure that x is not 0.
Last edited on Feb 24, 2012 at 3:10pm UTC
Feb 24, 2012 at 3:09pm UTC
Someone to verify this before I put a solved sign here?
HUMBLE REQUEST
Feb 24, 2012 at 3:11pm UTC
Oh okay...
I am just notching the Idea that is fine thank you ..... Thats the beauty of this forum everyone is ready to help. I,m Glad.
Thanks.