# Sum of first n terms of a series using c++

Suppose you have an arithmetic or a geometric series and you want to write a c++ code to calculate the sum of the first

*n*terms. There are lots of ways to solve this kind of problem. In this post I will discuss about a general approach, that can be applied for different kinds of series by changing only a single line in the code.

courtesy:scipp.ucsc.edu |

int z,n; double sum=0.0; /*I declare the sum as double, for general interest*/Next we will take the value for nth term as input

cout<<"input the value of n = "; cin>>n;After that we calculate the sum using a for loop.

for(z=1;z<=n;z++) { sum=sum+ z; //Change this line according to the series }Finally we get the output -

cout<<"the sum of "<<(z-1)<<" term = "<<sum<<endl;The full code would looks like this-

#include <iostream> using namespace std; int main() { int z,n; double sum=0.0; /*I declare the sum as double, for general interest*/ cout<<"input the value of n = "; cin>>n; for(z=1;z<=n;z++) { sum=sum+ z; //Change this line according to the series } cout<<"the sum of "<<(z-1)<<" term = "<<sum<<endl; return 0; }It wasn't so hard, right? Now what if you need to calculate the sum of the series of square numbers? i.e. $ s= 1^2+2^2+3^2+........+n^2$ ? No worries. By changing a single line of the above code you will get the answer.

If you look closely, you will see the original calculation occurs in line #21. So all we need to do is to change that to $z^2$. i.e-

sum=sum+ z*z;That's it. This will calculate the sum of the series of square numbers.

Let's say now you want to work with the fractions, something like $ s= 1+\frac{1}{2} +\frac{1}{3} +....... + \frac{1}{n}$. As before you just need to change the line #21 according to the series (in this case it's 1/z).

sum=sum+ 1/z;Got it? All you need to do is change the #21 according to the series. That's all for today's post.

If you understand the above code then try to solve these too-

- $ s= 1+\frac{1}{{2}^3} +\frac{1}{{3}^3} +....... + \frac{1}{{n}^3}$
- $ s= 1+2^2+2^3+........+2^n$
- $ s= 1+\frac{1}{{2}} +\frac{1}{{2}^2} +....... + \frac{1}{{2}^n}$