Sum of Series in C
C program to display sum of a series.
C program to display sum of a series.
Write a program to calculate the sum of the series: 1 – 2 + 3 – 4 + 5 – 6 + … + n.
Input:
Enter the number: 3
Output:
2
Explanation:
1 - 2 + 3 = 2
Input:
Enter the number: 0
Output:
Not allowed.
Input:
Enter the number: -2
Output:
Not allowed.
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. 🙂
To verify the program you have written, go ahead and test your program using the following test cases:
Input | Output | |
---|---|---|
Test Case 1 | 10 | -5 |
Test Case 2 | 1 | 1 |
Test Case 3 | 0 | Not allowed. |
Test Case 4 | -5 | Not allowed. |
Don’t forget to try the code on your own before diving into the 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