1

I'm currently reading the K&R book. Page 22, Arrays 1.6

int c, i, nwhite, nother;
int ndigit[10];

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

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

printf("digits =");
for(i = 0; i < 10; ++i)
    printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);

It says chars are considered integers. I tried removing the '0' in the first if satement. However, the array stopped working. If chars are considered to be integers, why is the '0' required for the program to function properly

Grayson
  • 17
  • 4
  • 1
    `0` is not `'0'` – Kevin May 16 '17 at 14:50
  • `c-'0'` is the short-hand way to get the digit from the ASCII digit. Since '0' is the lowest ASCII value, and digits are continuous in the ASCII encoding, subtracting `'0'` from a digit character gives you its value. – Scott Mermelstein May 16 '17 at 14:53
  • 1
    The character '0' (zero) has ASCII value 48 and is different from the NUL character '\0' which does have the numerical value 0. NB: C isn't bound to the ASCII standard but if you're using a computer that isn't someone should have told you. – Persixty May 16 '17 at 14:59
  • @DanAllen he subtracted '0' so that chars taken in as input actually represent the numbers they display. – AppWriter May 16 '17 at 15:19
  • @AppWriter But isn't that the point? Grayson doesn't know why this code (which presumably isn't theirs) needs to subtract '0' from something and thinks it's doing nothing because they think '0' is zero. – Persixty May 16 '17 at 15:30
  • "I tried removing the '0' in the first if satement." is unclear. `if(c >= && c<= '9')` does not compile. Post exactly the alternate code. Expand on "the array stopped working". – chux - Reinstate Monica May 16 '17 at 15:31

1 Answers1

0

Chars are numbers but '0' is not 0, but (in most cases) 48, '1' is not 1 but (in most cases) 49, and so on.

Here is the detailed explanation of it.

Community
  • 1
  • 1
MarianD
  • 13,096
  • 12
  • 42
  • 54