Name: Anonymous 2012-09-11 14:05
So, I'm workin on the book "The C Programming Language" when this code comes up under the chapter for character arrays:
It all makes sense, expect for the "++ndigit[c - '0'];" in line 14. I don't understand what this is doing, or why it has to do it. Shouldn't the program run the same if you didn't add the " - '0'" part? But when I take out that part, the program will compile, but it will return all '0' for every number, even if they are present.
So what exactly does subtracting '0' do for this program?
#include <stdio.h>
/* count digits, white space, others */
main()
{
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);
getchar();
}It all makes sense, expect for the "++ndigit[c - '0'];" in line 14. I don't understand what this is doing, or why it has to do it. Shouldn't the program run the same if you didn't add the " - '0'" part? But when I take out that part, the program will compile, but it will return all '0' for every number, even if they are present.
So what exactly does subtracting '0' do for this program?