Answer the question
In order to leave comments, you need to log in
Can you explain what ++ndigi[c-'0'] is doing here?
Here is the code that reads the numbers in the input stream (example from Kernighan's C programming textbook
#include
int main()
{
int nidigi[10],c,i;
for(i=0;i<10;++i)
nidigi[i]=0;
while ((c=getchar()) != EOF)
{
if(c>='0' && c<='9')
nidigi[c-'0']=nidigi[c- '0']+1;
printf("digits=")''
for (i=0;i<10;++i)
printf("%d",nidigi[i]);
}
return 0;
}
What does it mean this entry nidigi[c-'0']=nidigi[c-'0']+1;?I can't understand especially inside the brackets. We subtract from the symbol (if it is a number) the number zero or how?
Answer the question
In order to leave comments, you need to log in
The expression (c-'0') returns the index in the nidigi[10] array.
In variable
char c;
lies the ASCII code of the entered character (digit), if you subtract the ASCII code of the character '0' from this code, you will get a number from 0 to 9, which is what is required. To make sure, look at the table of ASCII codes.
In the nidigi array, as a result, the number of occurrences of decimal digits in the input data is a histogram.
'0' is not the number 0, but the character code "0". All but the very mammoth machines use supersets of the ASCII encoding, and '0' = 48.
Both in ASCII, and in EBCDIC, and in the internal encodings of, say, LCD displays, the digit codes go sequentially from 0 to 9 - so , subtracting the character code "0" from the code of the digit, we obtain the numerical value of the digit.
I.e ,
'0' - '0' = 48 - 48 = 0
'1' - '0' = 49 - 48 = 1
...
'9' - '0' = 57 - 48 = 9
(the numbers are valid for ASCII and its supersets, but in EBCDIC it is similar) Ord(c) - Ord('0')
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question