

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find sum of the series 1-2+3-4+5-6+7....in C++
In this problem, we are given an integer value N. Our task is to find Sum of Series 1 - 2 + 3 - 4 + 5 - 6 + 7 upto n terms.
The series is 1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 + 9 - 10...
Let's take an example to understand the problem,
Input : N = 4 Output : -2
Explanation −
1 - 2 + 3 - 4 = -2
Solution Approach
A simple approach to solve the problem is finding the general term of the series and then finding the sum till n terms. And calculating the sum using formula will reduce the time to O(1).
The series is,
1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 + 9 - 10...
Let's find the sum of series for some values,
sum(1) = 1
sum(2) = 1 - 2 = -1
sum(3) = 1 - 2 + 3 = 2
sum(4) = 1 - 2 + 3 - 4 = -2
sum(5) = 1 - 2 + 3 - 4 + 5 = 3
sum(6) = 1 - 2 + 3 - 4 + 5 - 6 = -3
sum(7) = 1 - 2 + 3 - 4 + 5 - 6 + 7 = 4
sum(8) = 1 - 2 + 3 - 4 + 5 - 6 + 7 - 8 = -4
For here, we can conclude that the sum can be formulated as,
Sum = +(n+1)/2 if n is odd.
Sum = -(n)/2 if n is even.
Example
Program to illustrate the working of our solution
#include<iostream> using namespace std; int calcSumNTerms(int n) { if(n%2 == 0) return ((-1)*(n/2)); return ((n+1)/2); } int main() { int n = 156; cout<<"The sum of series upto n terms is "<<calcSumNTerms(n); return 0; }
Output
The sum of series upto n terms is -78
- Related Questions & Answers
- Program to find sum of series 1 + 1/2 + 1/3 + 1/4 + .. + 1/n in C++
- C++ program to find the sum of the series 1 + 1/2^2 + 1/3^3 + …..+ 1/n^n
- Find sum of the series 1+22+333+4444+... upto n terms in C++
- Sum of the Series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... in C++\n
- Sum of the series 1 / 1 + (1 + 2) / (1 * 2) + (1 + 2 + 3) / (1 * 2 * 3) + … + upto n terms in C++
- Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + + (1+3+5+7+....+(2n-1)) in C++
- Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ...... + (1+3+5+7+...+(2n-1)) in C++
- Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n) in C++
- C++ program to find the sum of the series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!
- Sum of the series Kn + ( K(n-1) * (K-1)1 ) + ( K(n-2) * (K-1)2 ) + ... (K-1)n in C++
- Sum of the series 1^1 + 2^2 + 3^3 + ... + n^n using recursion in C++
- Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + .. + n in C++
- 8085 program to find the sum of a series
- Python program to find the sum of sine series
- Sum of the series 1, 3, 6, 10… (Triangular Numbers) in C++