Home »
C programs »
C sum of series programs
C program to calculate the sum of the series 1^3 -2^3 + 3^3 - 4^3 + ... N^3
In this program, we are going to learn how can we find the solution (calculate the sum) of the series 1^3 -2^3 + 3^3 - 4^3 + ... N^3, where N will be given by the user.
Submitted by IncludeHelp, on March 06, 2018
Calculating the sum of the series 1^3 -2^3 + 3^3 - 4^3 + ... N^3
To find the sum of this series using C program, we will read N by the user (which is the total number of terms) and run loop from 1 to N, within the loop body, we will check the condition for EVEN or ODD because, in this series ODD terms are being added and EVEN terms are being subtracting. Finally, we will print the calculate sum (result) of the series).
C program to find the sum of the series 1^3 -2^3 + 3^3 - 4^3 + ... N^3
#include <stdio.h>
#include <math.h>
int main()
{
int n; //total number of terms
int i; //loop counter
long int sum; //sum of the series
//read total number of terms
printf("Enter total number of terms: ");
scanf("%d",&n);
//assign 0 to the sum
sum = 0;
for(i=1; i<=n; i++){
//ODD terms are adding and
//EVEN terms are subtrating
if(i%2!=0)
sum = sum + pow(i,3);
else
sum = sum - pow(i,3);
}
//print sum of the series
printf("Sum of the series: %ld\n",sum);
return 0;
}
Output
Enter total number of terms: 5
Sum of the series: 81
Explanation
Series is: 1^3 -2^3 + 3^3 - 4^3 + ... N^3
Here, N = 5
Then the series will be:
= 1^3 -2^3 + 3^3 - 4^3 + 5^3
= 1 - 8 + 27 -64 + 125
= 81
C Sum of Series Programs »