C++ Online Compiler
Example: Basic Series Sum Calculator in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Basic Series Sum Calculator #include <iostream> class SeriesSumCalculator { private: int start; int end; int step; long long sum; // Use long long for potentially large sums public: // Constructor to initialize start, end, and step SeriesSumCalculator(int s, int e, int st) : start(s), end(e), step(st), sum(0) { // Ensure step is positive and not zero if (step <= 0) { std::cout << "Error: Step must be positive. Setting step to 1." << std::endl; this->step = 1; } } // Method to calculate the sum of the series void calculateSum() { if (start > end) { std::cout << "Warning: Start value is greater than end value. Sum will be 0." << std::endl; sum = 0; return; } for (int i = start; i <= end; i += step) { sum += i; } } // Method to get the calculated sum long long getSum() const { return sum; } }; int main() { // Step 1: Create an object for a series from 1 to 10 with step 1 SeriesSumCalculator s1(1, 10, 1); s1.calculateSum(); std::cout << "Sum of series (1 to 10, step 1): " << s1.getSum() << std::endl; // Step 2: Create an object for a series from 5 to 20 with step 2 SeriesSumCalculator s2(5, 20, 2); s2.calculateSum(); std::cout << "Sum of series (5 to 20, step 2): " << s2.getSum() << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS