Signup/Sign In

C++ Program To Find Sum Of Series 1 + x ^ 1 + x ^ 2 + x ^ 3 + . . . . . . . . . x ^ n

Here, in this tutorial, we will be seeing how to write the program for the given pattern and at the end print the resultant sum of the series formed for the input number of terms by the user.

C++ Program For The Sum of Series (First Method)

#include <bits/stdc++.h>
using namespace std;

double sum(int x, int n)
{
	double i, total = 1.0, multi = x;

	cout << total << " ";
	for (i = 1; i < n; i++) {

		total = total + multi;
		cout << multi << " ";
		multi = multi * x;
	}

	cout << "\n";
	return total;
}


int main()
{
	int x = 2;
	int n = 5;
	cout << fixed
		<< setprecision(2)
		<< sum(x, n);
	return 0;
}


1.00 2.00 4.00 8.00 16.00
31.00

C++ Program For The Sum of Series (Second Method)

#include<iostream>
#include<math.h>
using namespace std;

void main(){
long i,n,x,sum=1;

cout<<“1+x+x^2+……+x^n”;
cout<<“nnEnter the value of x and n:”;
cin>>x>>n;

for(i=1;i<=n;++i)
sum+=pow(x,i);
cout<<“nSum=”<<sum;
}


1.00 2.00 4.00 8.00 16.00
31.00

Conclusion

In this tutorial, we have learned the approach to implementing the given pattern or printing the sum with the help of an example. Both of the above methods take approximately the same amount of time.