Simple Geometric series 1+x+x^2+..+x^n – CSKC
Sign In

Search

Code Learning #CPP#2434    siteicon   siteicon  

Simple Geometric series 1+x+x^2+..+x^n

Printing the simple geometric series and finding its sum

Learning Objectives

  • Understanding the use of series looping methods for printing and summing the geometric progressions.
  • Use of pow() function for making a term of geometric progression.

Source Code

TC++ #2434

 

Source Code

×

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

Code Understanding

int x,n,y=0,sum=0;
x and n are declared to be collected by the user. y is used as increasing number for every iteration in the series. variable sum is used to calculate the sum of the series successively.

cout<<“Give x and n for (x^0..x^n) series :”;Β cin>>x>>n;
Here we collect x and n from the user.
for(int tc=1;tc<=n+1;++tc)
This loop starts from 1 and runs upto n+1 as power term y starts from 0. Alternative you may also write this to start from 0 and run till n.
{
int term=pow(x,y); //The power function is used to get the term of geometric progression.
cout<<term<<” “; //The term is printed here
sum+=term; //Sum is successively done in each iteration and the variable sum is updated.
y++; //The power term (exponent term) is increased so that it follow 0,1,2,3.. with each iteration.
}
cout<<endl<<“Sum of above series = “<<sum<<endl; //Sum is printed outside the loop

 

Notes

  • Geometric series of its generic form a+ar+ar^2+ar^3 ..Β  can also be built by the similar program with minor modification of using the given value of a is the pow() function multiplier.

Common Errors

  • Watch for this explanation for most common error a student can commit.
    for(int tc=1;tc<=n+1;++tc)

    This loop starts from 1 and runs upto n+1 as power term y starts from 0. Alternative you may also write this to start from 0 and run till n.


Suggested Filename(s): geo-ser.cpp



Share

Created: 10-Jan-2018 18:54 | Updated: 15-Sep-2018 13:18|