Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The sum of 1+(1-2)+(1-2+3)+(1-2+3-n)… where even integers are -k and odd integers are +k

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;
}

   

   

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading