Hi, everyone.
I am completely new to C programming and I have recently picked up K&R.
I am now reading section 1.6 Arrays, and the idea is to write a program to count the number of occurrences of each digit, of white spacecharacters (blank, tab, newline), and of all other characters.
In the example there is some code that I cannot understand, and I was hoping that someone could explain it to me.
Code:
if(a>='0' && a<='9')
++n[a-'0'];
The idea is that if the user inputs "1233",
the output will be "0 1 1 2 0 0 0 0 0 0", because there is 0 intances of "0", 1 instance of "1", and so on.
I would like to know why I have to add "-'0'" for the code to work. Could anyone please explain that to me?
I tried
Code:
if(a>='0' && a<='9')
++n[a];
and that did not work.