Search code examples
cimperative-programming

Exercise in C to calculate sum from x to y


My teacher wants the sum of all numbers from x to y... like x+(x+1)+(x+2)...until y. But I think I'm doing something wrong here!

Can someone advice me what is wrong here?

#include <stdio.h>

int sum_naturals(int n)
{
  return (n-1) * n / 2;
}

int sum_from_to(int m)
{
  return (m-1) * m / 2;
}

void test_sum_naturals(void)
{
  int x;
  scanf("%d", &x);
  int z = sum_naturals(x);
  printf("%d\n", z);
}

void test_sum_from_to(void)
{
   int x;
   int y;
   scanf("%d", &x);
   scanf("%d", &y);
   int z = sum_naturals(x);
   int b = sum_from_to(y);
   printf("%d\n", z);
}

 int main(void)
{
 //test_sum_naturals();
  test_sum_from_to();
  return 0;
}

Solution

  • Your code should in fact be:

    int sum_naturals(int n)
    {
        return (n+1) * n / 2;
    }
    
    int sum_from_to(int m)
    {
        return (m+1) * m / 2;
    }
    

    Notice + instead of your -.

    To find the sum just add in the function test_sum_from_to this line:

    printf("The sum is %d", b-z);