W
W
Whomai2018-05-09 14:08:48
C++ / C#
Whomai, 2018-05-09 14:08:48

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

3 answer(s)
R
res2001, 2018-05-09
@res2001

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.

M
Mercury13, 2018-05-09
@Mercury13

'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)
There is no concept of a "character" in the computer at all, and what is 48 - forty-eight parrots, the X-coordinate on the screen or the character code '0' - the programmer or compiler must think for himself . So C (which, in fact, is a cross-platform assembler), and it and Java put a very ephemeral line between one and the other. Unlike Pascal, where you need to write Ord(c) - Ord('0').

W
Whomai, 2018-05-09
@Whomai

Can you elaborate on the c-'0' expression? I still don't understand. It would be nice to give an example. (and I have not c)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question