C++ Online Compiler
Example: Sum of Series 1 1 2 1 3 ... in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Sum of Series 1 1 2 1 3 ... #include <iostream> using namespace std; int main() { // Step 1: Declare variables for the number of terms and the sum int n; long long sum = 0; // Use long long for sum to prevent potential overflow for large 'n' // Step 2: Prompt user for the number of terms cout << "Enter the number of terms (n) for the series: "; cin >> n; // Step 3: Input validation (optional, but good practice) if (n <= 0) { cout << "Please enter a positive integer for n." << endl; return 1; // Indicate an error } // Step 4: Loop through each term from 1 to n for (int i = 1; i <= n; ++i) { // Step 5: Check if the current position 'i' is odd or even if (i % 2 != 0) { // If 'i' is odd sum += (i + 1) / 2; } else { // If 'i' is even sum += 1; } } // Step 6: Display the calculated sum cout << "The sum of the series up to " << n << " terms is: " << sum << endl; return 0; }
Output
Clear
ADVERTISEMENTS