tags:

views:

284

answers:

8

The questions says 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

supposedly, the array stores incoming digit chars from the input stream...

A: 

getchar() is going to return the character code for the character as an int. Check out an ASCII chart such as: http://www.cs.utk.edu/~pham/ascii%5Ftable.jpg.

So if you enter '0' c is going to be 48. Subtracting '0' from the input value is just like subtracting 48, So you'll end up with the int values 0..9 in your integer array

DarkSquid
+8  A: 

It is creating a histogram of the characters 0-9. "c- '0'" turns the value from getchar() into an integer, which acts as the index for the array. This index corresponds to the numbers 0-9. It then increments that array location. Thus, once it has completed running, the array consists of the repetitions for the characters 0-9.

So 0123456789 should result in an array of all ones. 0123333 should result in an array with the values 1114000000.

Abtin Forouzandeh
+3  A: 

The character 0 is different from the number 0.

In ASCII, the character '0' is at position 48. The standard guarantees that in the character encoding, the numbers must be sequential (I do not know where in the standard this is said). That is, just like 1 comes after 0, '1' will come after '0'. Therefore, if you have entered '0', and you want to get 0, subtract '0' from it. '1' minus '0' will have a difference of 1. And so on.

GMan
+10  A: 

In C, you can do arithmetic on characters using their character codes. So this makes sure that you have a digit, finds out which digit it is (by measuring its difference from zero) and then increments a count in the corresponding position in the array. When it's done, ndigit[0] will contain the number of occurrences of '0', ndigit[1] will contain the number of occurrences of '1', and so on.

Pillsy
+1  A: 

c - '0' converts the character from its ASCII code to the value itself. That becomes the array index. The array subscript operator has a higher precedence than the preincrement, so the value in the array at the resulting index will be incremented.

Fred Larson
+1  A: 

The part [c - '0'] is creating a zero-based index for ndigit[]. It does this by taking c (which has an ASCII value in the range 48 to 57) and subtracting 48 (ASCII value of '0')

Eric J.
+1  A: 

Both POSIX and ISO C require:

The encoded values associated with the digits 0 to 9 shall be such that the value of each character after 0 shall be one greater than the value of the previous character.

Sinan Ünür
A: 

This is a incremental counter of inputed symbols from '0' to '9'.

e.g.

if u put '1' twice when ndigit[1] will 2, if u put '5' once when ndigit[5] will 1,
If u put '0' 5000000 times when ndigit[0] will 5000000 =)

... etc.