Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Sum of series 2/3 – 4/5 + 6/7 – 8/9 + ...... upto n terms
In C programming, we can calculate the sum of the series 2/3 − 4/5 + 6/7 − 8/9 + ...... up to n terms. This is an alternating series where each term has the form (-1)n+1 * (2*n) / (2*n + 1).
Syntax
double calculateSeriesSum(int n);
Understanding the Series Pattern
The series follows this pattern −
- First term: 2/3 (positive)
- Second term: -4/5 (negative)
- Third term: 6/7 (positive)
- Fourth term: -8/9 (negative)
For the nth term: (-1)n+1 * (2*n) / (2*n + 1)
Example: Calculate Series Sum
Here's a complete C program to calculate the sum of this series −
#include <stdio.h>
double calculateSeriesSum(int n) {
double sum = 0.0;
int sign = 1;
for (int i = 1; i <= n; i++) {
double term = (double)(2 * i) / (2 * i + 1);
sum += sign * term;
sign *= -1; // Alternate the sign
}
return sum;
}
int main() {
int n1 = 10, n2 = 17;
printf("For n = %d:<br>", n1);
printf("Sum = %.6f<br><br>", calculateSeriesSum(n1));
printf("For n = %d:<br>", n2);
printf("Sum = %.6f<br>", calculateSeriesSum(n2));
return 0;
}
For n = 10: Sum = -0.191921 For n = 17: Sum = 0.071520
How It Works
- We use a loop to generate each term of the series
- For each iteration i, the numerator is
2*iand denominator is2*i + 1 - We alternate the sign using a variable that switches between 1 and -1
- Each term is added to the running sum
Alternative Implementation
Here's another approach using the mathematical formula directly −
#include <stdio.h>
#include <math.h>
int main() {
int n = 10;
double sum = 0.0;
printf("Series: ");
for (int i = 1; i <= n; i++) {
double term = pow(-1, i + 1) * (2.0 * i) / (2 * i + 1);
sum += term;
if (i == 1) {
printf("%.0f/%d", 2.0 * i, 2 * i + 1);
} else {
printf(" %c %.0f/%d", (term > 0) ? '+' : '-',
fabs(2.0 * i), 2 * i + 1);
}
}
printf("\nSum = %.6f<br>", sum);
return 0;
}
Series: 2/3 - 4/5 + 6/7 - 8/9 + 10/11 - 12/13 + 14/15 - 16/17 + 18/19 - 20/21 Sum = -0.191921
Key Points
- The series alternates between positive and negative terms
- Each term follows the pattern
(2*n)/(2*n + 1) - Use
doubledata type for accurate floating-point calculations - The sign can be controlled using
pow(-1, i+1)or a toggle variable
Conclusion
This alternating series can be efficiently calculated using a simple loop that generates each term and maintains the alternating sign pattern. The sum converges to different values depending on the number of terms.
Advertisements
