1. ## K&R page 22

hello.
I put down teach yourself C in 21 days and have started over w/ the
K&R white book.
I'm trying to make sense of some code:
Code:
```int main (void)
{
int c, i, nwhite, nother;
int ndigit;

nwhite = nother = 0;
for ( i = 0; i < 10; ++i )
ndigit[i]=0;

while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];   //THIS LINE RIGHT HERE
else if ( c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;

printf("digits = ");
for( i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", whitespace = %d, other = %d\n",
nwhite, nother);
}```
I don't understand why the -'0' is there.
I understand that a character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set.
so '0' tranlates to 48
'1' translates to 49
if c = '1' then
c-'0' translates to 49-48 would equal 1
Why can't we use a 1 and a 9 in the code w/out the ' and having to subtract the value of '0' from it?
we define c as in int in the first line!
I hope i'm making sense. 2. getchar() returns an int; the ascii value of c

you could do this without - '0' but instead of '0' you would do - 48

the - '0' just lets you translate the ascii value into the actual int value

you seem to understand this pretty well based on the math you posted so I hope I am not making things more confusing 3. Isn't the point of that line of code to make the incremental count of ndigit get added to in the correct element of the array?

Meaning, if the the character checked is a digit, say 1, then 1 - 0 ( c - '0' ) is 1 so the ++ndigit adds a count to element ndigit.

Hence, if used on the code written for this program,:

ndigit = 9
ndigit = 3
ndigit = 1

all other elements in the array are equal to zero. 4. Originally Posted by noops getchar() returns an int; the ascii value of c

you could do this without - '0' but instead of '0' you would do - 48

the - '0' just lets you translate the ascii value into the actual int value

you seem to understand this pretty well based on the math you posted so I hope I am not making things more confusing
Just to note... if you subtract 48 instead of '0', your code will not be portable to non-ASCII systems (such as mainframes). Using c - '0' not only makes your code portable, but also much easier to understand. Popular pages Recent additions 