In the below program, I am curious why the array is indexed as ndigit[c-'0'] rather than just ndigit[c]. It seems the -'0' part is optional, since the intention is simply to increment the array at the index of c.
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'];
elseif (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);
}
is this from ritchie and kerninghams book? if so this is c and cant remember if its possible in c++ (there is a better c++ way at least) and what it does is in c is a char of range 0-9. in c if you do - '0' then it just becomes an int. ie '9'-'0'=9, '8'-'0'=8, etc. so its just going to cell (the int equivalent of char c) and incrementing by one. in c it is not optional
In the below program, I am curious why the array is indexed as ndigit[c-'0'] rather than just ndigit[c].
In C/C++, all arrays have 0 as the index of their first element. If c is the character '0', then its integer value is greater than 0 (you can look up ASCII code values if you want to know the exact number).
Subtracting the value of '0' from c normalises the integer values of the characters '0' to '9'. This means that c - '0' is 0 when c is '0', and is 1 when c is '1', and so on. If you used ndigit[c] then c would be a number much greater than 9, so ndigit[c] would be past the end of the array.