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 the first N terms of the series 2, 6, 12, 20, 30.... in c programming
In C programming, we can find the sum of the series 2, 6, 12, 20, 30… by analyzing its pattern. Each term can be expressed as n + n² where n is the position.
Syntax
sum = n*(n+1)/2 + n*(n+1)*(2*n+1)/6
Series Analysis
Let's analyze the given series −
The series can be split into two parts −
- Series 1: 1 + 2 + 3 + 4 + ... (Sum = n*(n+1)/2)
- Series 2: 1² + 2² + 3² + 4² + ... (Sum = n*(n+1)*(2*n+1)/6)
Example
Here's a complete program to calculate the sum of first N terms −
#include <stdio.h>
int main() {
int n = 5;
int sum1 = (n * (n + 1)) / 2; /* Sum of 1+2+3+...+n */
int sum2 = (n * (n + 1) * (2 * n + 1)) / 6; /* Sum of 1²+2²+3²+...+n² */
int total_sum = sum1 + sum2;
printf("First %d terms of series: ", n);
for(int i = 1; i <= n; i++) {
printf("%d ", i + i*i);
if(i < n) printf("+ ");
}
printf("<br>");
printf("Sum of first %d terms = %d<br>", n, total_sum);
return 0;
}
First 5 terms of series: 2 + 6 + 12 + 20 + 30 Sum of first 5 terms = 70
Method 2: Using Loop
We can also calculate the sum using a simple loop −
#include <stdio.h>
int main() {
int n = 6;
int sum = 0;
printf("Series terms: ");
for(int i = 1; i <= n; i++) {
int term = i + (i * i);
sum += term;
printf("%d ", term);
if(i < n) printf("+ ");
}
printf("<br>");
printf("Sum of first %d terms = %d<br>", n, sum);
return 0;
}
Series terms: 2 + 6 + 12 + 20 + 30 + 42 Sum of first 6 terms = 112
Key Points
- The mathematical formula approach has O(1) time complexity
- The loop approach has O(n) time complexity but is more intuitive
- Both methods produce the same result for any positive integer n
Conclusion
The sum of the series 2, 6, 12, 20, 30… can be calculated efficiently using the mathematical formula or through iterative addition. The formula method is faster for large values of n.
Advertisements
