C: unable to understand the following array assignment

Questions say it all:

...
int ndigit[10];
...//fill in the array with 0s

while((c = getchar()) != EOF)
    if(c >= '0' && c <= '9')
         ++ndigit[c - '0']; //<== unable to understand this part

presumably the array stores the incoming digits of the digits from the input stream ...

+5
source share
9 answers

In C, you can do arithmetic on characters using your character codes. Thus, this ensures that you have a digit, it turns out which digit it is (by measuring its difference from zero), and then increases the score at the corresponding position in the array. When this is done, it ndigit[0]will contain the number of entries '0', ndigit[1]will contain the number of entries '1', etc.

+12
source

0-9. "c-" 0 "" getchar() , . 0-9. . , 0-9.

0123456789 . 0123333 1114000000.

+8

0 0.

ASCII "0" 48. , ( , ). , 1 0, "1" "0". , "0" 0, "0". "1" "0" 1. .

+6

getchar() int. ASCII, : http://www.cs.utk.edu/~pham/ascii_table.jpg.

, "0", 48. "0" 48, int 0..9

+1

c - '0' ASCII . . , , .

+1

[c - '0'] ndigit []. , c ( ASCII 48 57) 48 ( ASCII '0 ")

+1

POSIX ISO C :

, 0 9 , 0 , .

+1

"0" "9".

.

u '1' , ndigit [1] 2, u '5' , ndigit [5] 1,
u '0' 5000000 , ndigit [0] 5000000 =)

... etc.

0
source

I can't comment or vote since I'm new, but just wanted to say thanks @Eric J, @DarkSquid and @GManNickG. I understand how indexing works, but was still confused. These answers really clarified this for me. The book was very clear and concise up to this point, it seems they could better explain why it is necessary -'0'from [c-'0'].

-2
source

All Articles