is the following program correct for the title 1/1!+1/3!+1/5!+.....+1/n!

#include<iostream.h>
#include<conio.h>
class series
{
int i,n,sum,fact; 
public:
void input()
{
cout<<"enter the number of terms";
cin>>n;
}
void processing()
{
if(n%2==0)
{
cout<<"the number is invalid";
}
else
{
i=1,sum=0;
      while(i<=n)
      {
       sum+=(1/factorial(i););
       i+2;
       }
 }
}
int factorial(int lim)
{
int j;
fact=0;
for(j=1;j<=lim;j++)
fact*=j;
return fact;
}
void output()
{
cout<<"the sum of the series is"<<sum;
}
};
void main()
{
series se;
clrscr();
se.input();
se.processing();
se.output();
getch();
}

i programmed it myself!!! i think it's correct, but i wish to check all the same.. i impressed my teacher yesterday in c++ class *blushing* :) :) :P

Recommended Answers

All 3 Replies

well <iostream.h> and <conio.h> are old and deprecated libraries
It's better when you use a modern library like <iostream>

also since you didn't bother to wrap the code in code tags it's hard to tell if you did a good job

sum+=(1/factorial(i)) ; Is integer division ok here?

A more efficient way to sum up this series would be to use the recurrence relation between successive terms.
1/1! + 1/3! + 1/5! + ... = a<0> + a<1> + a<2> + ...
a<0> = 1 ; a<1> = a<0> / (2*3), a<2> = a<1> / (4*5)
etc.
In general, we have the recurrence relation: a<i> = a<i-1> / ( (i*2) * (i*2+1) )

double sum = 1.0 ;
double term = 1.0 ;
for i in [1,n-1]
    compute and set new value of term using the recurrence relation
    add term to sum
end for

Ummm...guys this is a very basic code.. using very basic and outdated libraries...
Inference : Shes using Borland Turbo C++ Ver 3.0
This is mostly used by almost all schools, colleges, universities to start out with the basics !!

Coming To Program Execution
The program is incorrect, it doesnt execute giving a divide error...( COmpiled on Turbo C++)
I dint take the time to read through the code and see if the logic is correct or not as it gave a divide error, so its certainly not !! So, im really sorry but ull have to come up with another way of doing it..

The noticeable error i found was in line 23
There is an extra semicolon, the corrected line is thus :
sum+=(1/factorial(i));

I've done this program many a times before, its part of the first year syllabus... Try it once, if not.. ill post the code for u !!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.