I want to write a program where a user tells me an integer(n) and i calculate The sum of 1 (1-2) (1-2 3) (1-2 3-n)... where even integers are -k and odd integers are k.
Ive made a function which does that But the sum is never correct. For example for n=2 it should be sum=0 but shows sum=-1 for n=3 should be sum= 2 but i shows sum=3. (Ignore the debugging printfs)
#include <stdio.h>
int athroismaAkolouthias(int n); // i sinartisi me tin opoia ypologizete to athroisma akolouthias 1 (1-2) (1-2 3) (1-2 3-4).....
int main(){
int n;
printf("give n: ");
scanf("%d", &n);
printf("the sum is %d", athroismaAkolouthias(n));
}
int athroismaAkolouthias(int n){
int sum1=0, sum2=0,sum=0;
int i, temp, j;
for (i=1; i<=n; i ){
for (j=1; j<=i; j ){
temp=j;
}
if (i%2==0){sum=sum-temp; printf("test1 %d%d",sum,temp);}
else{sum=temp; printf("test2 %d%d",sum,temp);}
}
return sum;
}
CodePudding user response:
Your issue is with our loop which iterate with j
, it should update the inner_sum
based on j
even/odd condition as follows:
#include <stdio.h>
int akl(int n) {
int sum = 0;
for (int i = 1; i <= n; i ) {
int inner_sum = 0;
for (int j = 1; j <= i; j ) {
if (j % 2 == 0) {
inner_sum -= j;
} else {
inner_sum = j;
}
}
sum = inner_sum;
}
return sum;
}
int main() {
int n;
scanf("%d", &n);
printf("%d\n", akl(n));
}
You only need two variables for sum
that I named them inner_sum
and sum
which shows the sum of each term and sum over all terms.
CodePudding user response:
Suspicious Line: else {sum = temp; ...
Shouldn't you be adding or subtracting to sum
every time??
Why are you assigning to it here, without an addition or subtraction?
You also have variables sum
, sum1
, and sum2
.
You print sum1
and sum2
, but never modify them.
Here's my solution:
// The sum of 1 (1-2) (1-2 3) (1-2 3-n)... where even integers are -k and odd integers are k.
#include <stdio.h>
int ancho(int n)
{
int sum=0;
for(int i=1; i<=n; i)
{
for(int j=1; j<=i; j)
{
sum = (2*(j%2)-1)*j;
}
}
return sum;
}
int main(void)
{
int n = 5;
printf("Solution is %d\n", ancho(n));
}
// Solution is 3 for n = 5,
// because: 1 (1-2) (1-2 3) (1-2 3-4) (1-2 3-4 5) =
// 1-1 2-2 3 = 3
Output
Success #stdin #stdout 0s 5476KB
Solution is 3