Printing and summing series 1/n! form. – CSKC
Sign In

Search

Solved Problem #CPP#2443    siteicon   siteicon  

Problem Statement - Printing and summing series 1/n! form.

Write a program to find the sum of the following series upto 5 terms. Also print the series terms.
1/1! + 2/2! + …

Solution

TC++ #2443

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

int x=1,n=5;
variable x is used as the base variable which is increased from 1 on wards. variable n keeps numbers of terms to be printed.
float sum=0;
//The sum can be a fraction as terms are fractions so float type taken
for(int tc=1;tc<=n;++tc)
For printing and summing 5 term series 1 to n (5) has been taken
{
int f=1;
This will keep the factorial term so it has to be updated to 1 after printing each term.
for(int i=1;i<=x;++i)
This is factorial finding nested loop. This runs from 1 to current value of x as decided by iteration.
{
f*=i; 
//This is simple successive multiplication for factorial finding.
}
float term=float(1)/f;
This is term expression building based on given formula 1/n! . The denominator has f as it contains the factorial of given number. The upper term has been type casted a float to ensure that resultant value is a fraction value.
cout<<term<<” “;
//The term is printed.
sum+=term;
//The successive sum od term is deduced
x++;
//x is incremented for next term calculation
}
cout<<endl<<“Sum of above series = “<<sum<<endl; //Sum is printed outside the loop

 

Notes

  • Factorial calculation in such program can be done using an external function to make it a neat program.

Common Errors

  • The term expressions which are of fraction types should necessarily be computed in float or double data type. If this is not done the integer division may either result in 0 or it may trim of fractional portion of the term.
  • int f=1 again after each iteration of outer loop is extremely important, other wise previous value of f will be retained and factorial of new x will be erroneous.


Suggested Filename(s): geo-ser.cpp



Share

Created: 10-Jan-2018 20:35 | Updated: 18-Dec-2018 18:58|