C++ Online Compiler
Example: Sum of Series (Iterative, with std::pow) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Series (Iterative, with std::pow) #include <iostream> #include <cmath> // For std::pow #include <iomanip> // For std::fixed and std::setprecision using namespace std; int main() { // Step 1: Declare variables for x, n, and sum double x; int n; double sum = 0.0; // Step 2: Prompt user for input cout << "Enter the value of x: "; cin >> x; cout << "Enter the number of terms (n): "; cin >> n; // Step 3: Input validation if (n <= 0) { cout << "Number of terms (n) must be positive." << endl; return 1; } // Step 4: Iterate to calculate sum using std::pow for (int i = 0; i < n; ++i) { sum += pow(x, i); // Add x^i to the sum } // Step 5: Display the result cout << fixed << setprecision(6); // Set precision for output cout << "Sum of the series for x = " << x << " and n = " << n << " is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS