blaxjax
blaxjax

Reputation: 13

Trouble making a running total in C

I'm new at programming, new on this site too, so hello... I'm attempting to obtain a running total for integers one thru 10, but I'm getting gibberish answers and I just can't understand why. To attempt to find out what was going wrong, I added the

printf(" running total is %d\n", sum);

line to the while loop, but just got more of the same nonsense... please see http://codepad.org/UxEw6pFU for the results....

I'm sure this has a blindingly obvious solution...I'm just too dumb to see it though! anyone know what I'm doing wrong?

#include <stdio.h>


int main(void)      {

    int count,sum,square;           
    int upto=10;                 

    count = 0;                
    square = 0;                 

    while (++count < upto)   {   
        square = count * count;
        printf("square of %d is %d",count,square);     
        sum =square + sum;
        printf(" running total is %d\n", sum);
    }

    printf("overall total of squares of integers 1 thru 10 is %d\n", sum);           

    return 0;
}

Upvotes: 1

Views: 4109

Answers (6)

NG.
NG.

Reputation: 22914

You need to initialize sum to 0.

EDIT As others have stated after the fact, the reason you're seeing garbage is because sum isn't initialized and contains whatever is in memory. It can be anything, and your use of it with sum = square + sum is going to add square to the uninitialized value.

Upvotes: 9

wkl
wkl

Reputation: 80001

Right off the bat, you do not initialize 'sum' to anything.

edit: A cleaned up version, though depending on compiler, you might need to enforce C99 mode, otherwise older compilers might not support initial declarations in the for loop.

#include <stdio.h>

int main()
{

    const int COUNT_MAX = 10;
    int sum = 0;

    for ( int i = 1; i <= COUNT_MAX; ++i )
    {
        sum += i*i;
    }

    printf("The sum of squares from 1 to 10 is: %d\n", sum);

    return 0;
}

Upvotes: 1

user379888
user379888

Reputation:

You should do :

sum=0;

and remove

square=0;

Upvotes: 0

dimba
dimba

Reputation: 27611

sum is not initialized

Upvotes: 0

Tyler McHenry
Tyler McHenry

Reputation: 76710

You are never initializing the value of sum.

The first time your code runs

sum = square + sum;

The value of sum (on the right side) is an arbitrary number because it has not been initialized. Therefore, the resulting value of sum (on the left side) is that arbitrary number plus square.

Simply add a sum = 0 statement like you have for count and square already.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816780

Initialize sum with 0, otherwise it contains arbitrary data:

sum = 0;

See: http://codepad.org/e8pziVHm

Upvotes: 0

Related Questions