C++ Online Compiler
Example: Sum of Series (Iterative, without pow) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Series (Iterative, without pow) #include <iostream> #include <iomanip> // For std::fixed and std::setprecision using namespace std; int main() { // Step 1: Declare variables for x, n, sum, and current term double x; int n; double sum = 0.0; double currentTerm = 1.0; // The first term is x^0 = 1 // 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 for (int i = 0; i < n; ++i) { sum += currentTerm; // Add the current term to the sum currentTerm *= x; // Calculate the next term } // 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