C: unable to understand the following array assignment
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.
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.
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.