# Thread: sum is always printed as 0

1. ## sum is always printed as 0

I just can't seem to figure this out. My program is: Put unlimited characters until you put " ! ". If there are numbers in those characters, calculate their sum.
Code:
```
#include <stdio.h>
int main()
{
char character;
int digit = 0,sum=0;
while(1){
digit = 0;
scanf("%c", &character);
if(character=='!')
break; // Put unlimited characters until '!'
if(character>='0' && character<='9') // Check if the character is a digit
{
digit=(int)character; // Store it
}

sum+=digit;
}

printf("%d", sum);
return 0;
}```
In the code above, i always get sum = 0. What is the problem? 2. I don't know why it's printing 0 for you. The way it's written it should be giving you the sum of the ascii values of all the digit characters it's seen before the bang. That's what it does for me. The input 0123456789! prints 525, the sum of 48, 49, ..., 57, the ascii values of '0', '1', ..., '9'.

Remember that the numeric value of, e.g., '7' is '7' - '0'. Also note that to read a multi-digit number (if that's your purpose) requires you to accumulate that value for each digit, multiplying the old value by 10 and adding in the newest digit. Then when you encounter a non-digit and the accumulated value is non-zero, add it into sum and reset it to zero for the next number. 3. Clearer indentation would help.
Code:
```#include <stdio.h>

int main()
{
char character;
int digit = 0, sum = 0;

while (1) {
digit = 0;
scanf("%c", &character);
if (character == '!')
break;                    // Put unlimited characters until '!'
if (character >= '0' && character <= '9') // Check if the character is a digit
{
digit = (int) character;  // Store it
}
sum += digit;
}

printf("%d", sum);
return 0;
}``` Popular pages Recent additions characters, int, put, sum, unlimited 