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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With