Sum of Series in C

C program to display sum of a series.


Problem

Write a program to calculate the sum of the series: 1 – 2 + 3 – 4 + 5 – 6 + … + n.

Example 1:

Input:
Enter the number: 3

Output:
2

Explanation:
1 - 2 + 3 = 2

Example 2:

Input:
Enter the number: 0

Output:
Not allowed.

Example 3:

Input:
Enter the number: -2 

Output:
Not allowed.

Expectations:

You need to write the complete program using the following template as the starter:

#include <stdio.h>

int main() {
    int n;

    printf("Enter the number: ");
    scanf("%d", &n);
    
    // Write your code here 
    
    return 0;
}

Copy and paste the above code in your favorite IDE and start writing your code after the comment “// Write your code here.”

Pro tip:  First, try writing the code on your own. Try every possible thing you can to come up with the solution. If you still can’t figure it out, then check the solution and see what went wrong. This is how you learn. 🙂

Sample Test Cases:

To verify the program you have written, go ahead and test your program using the following test cases:

InputOutput
Test Case 110-5
Test Case 211
Test Case 30Not allowed.
Test Case 4-5Not allowed.

Don’t forget to try the code on your own before diving into the solution.


Solution

The following program is used to calculate the sum of series according to the problem statement:

// Program: Sum of series 1 - 2 + 3 - 4 + 5 - ... n
#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    
    printf("Enter the number: ");
    scanf("%d", &n);
    
    // Write your code here.
    
    int sum = 0, sign = 1;
    
    // Check for zero or negative numbers
    if (n <= 0) {
        printf("Not allowed.");
        exit(0); // Exit with FAILURE 
    }
    
    // main logic
    for (int i = 1; i <= n; i++) {
        // add a number to the previous sum
        sum += i * sign;
        sign = -sign; // toggle the sign
    }
    
    printf("%d", sum);
    return 0;
}

Inside the for loop, the current number (represented by the loop variable i) is added to the old sum in each iteration, but first it gets multiplied by the current sign. Initially, sign is positive as the first number of the series is positive. The subsequent numbers have toggled signs, therefore, after every addition, the sign is changed. Hence, we will get the correct sum as the result at the end.



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.