Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: unable to understand the following array assignment

Tags:

arrays

c

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...

like image 962
Midnight Blue Avatar asked Aug 17 '09 22:08

Midnight Blue


2 Answers

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.

like image 111
Pillsy Avatar answered Nov 15 '22 09:11

Pillsy


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.

like image 30
Abtin Forouzandeh Avatar answered Nov 15 '22 07:11

Abtin Forouzandeh