×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to calculate the sum of the series 1-2+3-4+5-6+7-8...N terms

Given the series 1 -2+3-4+5-6+7-8 ... N terms, and we have to find the sum of all values using C program.
Submitted by Anshuman Das, on September 12, 2019

Problem statement

The series is: 1-2+3-4+5-6+7-8...N terms, we have to find out the sum up to Nth terms.

Solution

Let's analyse this problem,

If we want Sum of this series up to 2nd term then sum will be:
    1-2 =-1
Up to 3rd term:
    1-2+3 =2
Up to 4th term 
    1-2+3-4 = -2
Up to 5th term:
    1-2+3-4+5= 3
    .
    .
    .

Now we can conclude that if we want sum up to an Odd term then we always get sum as ((N+1)/2) and if we want sum up to an Even term the sum is in the form of (-1*(N/2)).

C program to calculate the sum of the series 1-2+3-4+5-6+7-8...N terms

Now Let's make logic for this using c programming,

#include <stdio.h>

//function for creating the sum of the 
//series up to Nth term
int series_sum(int n)
{
    if (n % 2 == 0)
        return (-(n / 2));
    else
        return ((n + 1) / 2);
}

// main code
int main()
{
    int n;
    printf("Series:1-2+3-4+5-6+7-8.....N\n");
    printf("Want some up to N terms?\nEnter the N term:");
    scanf("%d", &n);
    
    printf("Sum is:%d", series_sum(n));
    
    return 0;
}

Output

Series:1-2+3-4+5-6+7-8.....N
Want some up to N terms?
Enter the N term:10
Sum is:-5

C Sum of Series Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.