# Thread: How can I use arrays to count instances?

1. ## How can I use arrays to count instances?

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.

2. Originally Posted by Ceasar
I would like to know why I have to add "-'0'" for the code to work. Could anyone please explain that to me?
A character like '0' has some value, e.g., 48 in ASCII and its derivatives. It is also guaranteed that the characters that represent the digits will have contiguous values in order, e.g., if '0' is 48, then '1' will be 49, '2' will be 50, etc. Therefore, given a variable a that you know contains the character value of a digit, you can obtain the mathematical value of the digit by subtracting the character value of 0, i.e., if '0' is 48, you can use a - 48 to obtain 0. But why rely on the magic number 48, especially since it is not guaranteed that '0' == 48? Hence, we use a - '0'.

3. Thank you for a very nice explanation, laserlight!