Bruno Rodrigues
Bruno Rodrigues

Reputation: 69

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

Upvotes: 0

Views: 256

Answers (2)

Igor Pejic
Igor Pejic

Reputation: 3698

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

Upvotes: 1

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

Here's one solution :

#include<stdio.h>

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

int sum_from_x_to_y(int x, int y){
    return sum_naturals(y) - sum_naturals(x);
}

main()
{
     printf ("Sum: %d \n",sum_from_x_to_y(5, 10));
     printf ("Sum: %d \n",sum_from_x_to_y(0, 10));
     printf ("Sum: %d \n",sum_from_x_to_y(0, 5));
    return 0;
}

Note : sum from 0 to N is (n+1)*n/2 and not (n-1)*n/2

Upvotes: 1

Related Questions