-10

So I'm writing a program about finding the sum number of all ranges for instance, if I enter a 1 and then a 10 it should display 55, but instead it display some long random number. Does anyone have a clue what's wrong with this code? Thanks!

#define <stdio.h>

calculateSum(int lowNumber, int highNumber);

int main()
{
   int lowerNumber,
       higherNumber;

   scanf("%d", lowerNumber);
   scanf("%d", higherNumber);

   printf("The sum of all ranges is: %d", calculateSum(lowerNumber, higherNumber));

int calculateSum(int lowNumber, int highNumber)
{
    int total;

    for(int x = lowNumber; x <= highNumber; x++)
    {
       total = total + x;
    }
    return total;
}
Paul
  • 11
  • 4
  • 2
    this isn't valid C. `#define ` ? Shouldn't it be `#include` ? Also your main fn isn't closed before you start the next fn. Also set `total` to 0 before you use it – Srini Sep 06 '18 at 21:36
  • In `calculateSum`, You're not initializing `total`, so its initial value is random. Use `int total = 0;` to set it correctly – Craig Estey Sep 06 '18 at 21:37

3 Answers3

1

You're not initializing total before its first use as a rvalue (which is the RHS of assignment total = total + x;) thus its value remains undefined (and indeterminate.)

bipll
  • 11,747
  • 1
  • 18
  • 32
1

In addition to @biplls answer there is also another issue:

int lowerNumber,
   higherNumber;

scanf("%d", lowerNumber);
scanf("%d", higherNumber);

is UB (produces a warning on compilation and a SEGFAULT during runtime). printf expects an int*, not int. The correct code would be

int lowerNumber,
   higherNumber;

scanf("%d", &lowerNumber);
scanf("%d", &higherNumber);
1

A few errors here

  1. it's #include <stdio.h> not #define
  2. When using scanf you have to add an & before the var you read into (in this case!! )
  3. The main fn doesn't return anything, it should be returning 0 (normally) (apparently I'm wrong on this , main returns 0 implicitly from C99)
  4. Main fn isn't closed before you write the next fn
  5. total should be set to 0
  6. for loop initialization is allowed only in C99
  7. It is a good idea to declare the return type of the prototype

fixing all this

#include <stdio.h>

int calculateSum(int lowNumber, int highNumber);

int main()
{
   int lowerNumber,
       higherNumber;

   scanf("%d", &lowerNumber);
   scanf("%d", &higherNumber);

   printf("The sum of all ranges is: %d\n", calculateSum(lowerNumber, higherNumber));
   return 0;
}

int calculateSum(int lowNumber, int highNumber)
{
    int total;
    total = 0;

    for(int x = lowNumber; x <= highNumber; x++)
    {
       total = total + x;
    }
    return total;
}

Running the above

$ ./sum
1
10
The sum of all ranges is: 55
Srini
  • 1,619
  • 1
  • 19
  • 34