C++ Online Compiler
Example: Sum of Series (Geometric Formula) in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Series (Geometric Formula) #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: Apply the geometric series formula if (x == 1.0) { // If x is 1, each term is 1, so sum is n * 1 sum = n; } else { // Use the formula: S = (x^n - 1) / (x - 1) sum = (pow(x, n) - 1.0) / (x - 1.0); } // 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