#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);
}
Why is it, on line 12, ++ndigit[c-'0']; is used instead of just ++ndigit[c];?
Name:
Anonymous2010-01-24 12:40
Because ASCII values 0-9 are NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS and HT.
Name:
Anonymous2010-01-24 12:41
cool indentation
The ASCII code for 0 is 48 I believe and all the other numbers are after that.
So if c is say '8' that expression would be 56 - 48 which is 8, the position you want.
Name:
Anonymous2010-01-24 12:41
Because if c is a character, the '0' character represents the number 48, '1' = 49, etc. Since the array is only size 10, accessing index 48 would be an out of bounds reference. By subtracting '0', you reduce the range to 0-9, which are the fight indices.