Reputation: 5
New to C and I need some guidance. I understand why the my code is outputting "55" instead of "40"; but I have no idea how to fix this. Any advice? Some of the variables listed are obsolete, and were simply put in to experiment with. Just to clarify, lower/upper are just the min/max values for the range.
#include<stdio.h>
#include<stdlib.h>
int sum = 0;
int main() {
int n = 10;
int m = 2;
int i, x;
int upper;
int lower;
int lower1[100];
int upper1[100];
int sum_p =0;
for (i = 1; i <= m; i++) {
lower = 1 + (i - 1) * (n / m);
lower1[i] = lower;
upper = i * (n / m);
upper1[i] = upper;
if (i == m) {
upper = n;
upper1[i] = upper;
}
else {
upper = i * (n / m);
upper1[i] = upper;
}
}
for (i = 1; i <= n; ++i) {
sum += i;
}
printf("The total sum is: %d\n",sum);
for (i = 1; i <= m; i++) {
printf("Range is %d to %d\n", lower1[i], upper1[i]);
for(x = lower1[i]; x <= upper1[i]; ++x)
sum_p += x;
printf("Sum:%d\n",sum_p);
}
}
This code outputs:
The total sum is: 55
Range is 1 to 5
Sum:15
Range is 6 to 10
Sum:55
My desired output is:
The total sum is: 55
Range is 1 to 5
Sum: 15
Range is 6 to 10 /*6+7+8+9+10*/
Sum: 40
Upvotes: 0
Views: 67