1. ## code understanding

Hey I m reading K&R but this code there some stuff in it whish i dont understand it suppose to be an space counter and num from 0 to 9 thingy so please anyone help thanks
Code:
```#include <stdio.h>
/* count digits, white space, others */
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'];
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);
return 0;
}```
i dont understand this line
++ndigit[c-'0'];
why did he do c-'0'
i have read K&R carefully but still didnt understand why did he do that 2. All that code is doing is incrementing the index that matches what the user types in. So if the user types in the character '1', then it is incrementing that index of ndigit.

It might be easier to understand if it is broken up into a couple lines.
Code:
```// Convert the ascii character '0'-'9' to an integer from 0-9.
int index = c-'0';
// Increment that index of the array
ndigit[index] = ndigit[index] + 1;``` 3. Originally Posted by elwad i dont understand this line
++ndigit[c-'0'];
why did he do c-'0'
i have read K&R carefully but still didnt understand why did he do that
c-'0' only converts the inputted digit to its decimal form.suppose you enter 6, in that case c='6' and the numeric value that c holds will be ASCII of '6'(which is 54 i think) so just to make it a 6 it does c-'0'(which is '6'-'0'==54-48(=6)).it can be done only for those encodings which have their characters '0' to '9' in an increasing order(by 1),which is true in the case of ASCII and for others also i think. 4. but why c-'0' why dont he just cast it (int)c; ?will it be the same coz i dont see when he does '6'-'0' the output will still be 6 so whats the diff ? 5. Originally Posted by elwad but why c-'0' why dont he just cast it (int)c; ?will it be the same coz i dont see when he does '6'-'0' the output will still be 6 so whats the diff ?
Because (int)c will be '6' still - just 32 instead of 8 bits long. '6' is the same as 54 as an integer, and that is well outside your 0..9 range that is OK for the ndigit array. By subtracting the '0' value, we get a range from 0..9, which is valid. We could of course have an array that is 58 elements long, and only use the last 10 of those, but that's not very efficient, right?

--
Mats 6. yah I get it now thanks. Popular pages Recent additions 