C++ Exercises: Find the sum of the series [ x - x^3 + x^5 + ......]
C++ Exercises: For Loop Exercise-25 with Solution
Write a program in C++ to find the sum of the series [ x - x^3 + x^5 + ......].
Sample Solution:-
C++ Code :
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float x, sum, ctr;
int i, n, m, mm, nn = 0;
cout << "\n\n Display the sum of the series [ x - x^3 + x^5 + ......]\n";
cout << "------------------------------------------------------------\n";
cout << " Input the value of x: ";
cin >> x;
cout << " Input number of terms: ";
cin >> n;
sum = x;
m = -1;
cout << "The values of series:" << endl;
cout << sum << endl;
for (i = 1; i < n; i++) {
ctr = (2 * i + 1);
mm = pow(x, ctr);
nn = mm * m;
cout << nn << endl;
sum = sum + nn;
m = m * (-1);
}
cout << "\n The sum of the series upto " << n << " term is: " << sum << endl;
}
Sample Output:
Display the sum of the series [ x - x^3 + x^5 + ......] ------------------------------------------------------------ Input the value of x: 2 Input number of terms: 5 The values of series: 2 -8 32 -128 512 The sum of the series upto 5 term is: 410
Flowchart:
![Flowchart: Find the sum of the series [ x - x^3 + x^5 + ......]](https://www.w3resource.com/w3r_images/cpp-for-loop-exercise-25.png)
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to display the sum of the series [ 1+x+x^2/2!+x^3/3!+....].
Next: Write a program in C++ to find the sum of the series 1 +11 + 111 + 1111 + .. n terms.
What is the difficulty level of this exercise?
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join