I\'m a novice in C and I came across the code like this :
int n[10];
if(c>=\'0\' && c<=\'9\')
++n[c-\'0\']
In if
'0'
and '9'
are of int
types. Their values are 48 and 57 respectively (since 48 and 57 are ASCII values of characters '0'
and '9'
).
So you are probably holding in n
an array for counting digits.
So this expression (if you are storing digit characters on c
):
++n[c-'0'];
Means:
c-'0'
(c
holds a character with a digit on it)So n
will be:
n[0] = x; // count of 0 characters
n[1] = x; // count of 1 characters
n[2] = x; // count of 2 characters
n[3] = x; // count of 3 characters
n[4] = x; // count of 4 characters
n[5] = x; // count of 5 characters
n[6] = x; // count of 6 characters
n[7] = x; // count of 7 characters
n[8] = x; // count of 8 characters
n[9] = x; // count of 9 characters
For example, let's say c
is equal to character 2
. 2
's ascii value is 50
. So n[50-48]
becomes n[2]
. So you end up using third element of array n
to store 2
character count.