Trouble making a running total in C -


i'm new @ programming, new on site too, hello... i'm attempting obtain running total integers 1 thru 10, i'm getting gibberish answers , can't understand why. attempt find out going wrong, added

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

line while loop, got more of same nonsense... please see http://codepad.org/uxew6pfu results....

i'm sure has blindingly obvious solution...i'm dumb see though! know 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 %d",count,square);              sum =square + sum;         printf(" running total %d\n", sum);     }      printf("overall total of squares of integers 1 thru 10 %d\n", sum);                 return 0; } 

you need initialize sum 0.

edit others have stated after fact, reason you're seeing garbage because sum isn't initialized , contains whatever in memory. can anything, , use of sum = square + sum going add square uninitialized value.


Comments

Popular posts from this blog

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -

openssl - Load PKCS#8 binary key into Ruby -