indexing arrays

Nov 21, 2013 at 5:39am
In the below program, I am curious why the array is indexed as ndigit[c-'0'] rather than just ndigit[c]. It seems the -'0' part is optional, since the intention is simply to increment the array at the index of c.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
main()
{
    int c, i, nwhite, nother;
    int ndigit[10];

    nwhite = nother = 0;
    for (i = 0; i < 10; ++i)
        ndigit[i] = 0;

    while ((c = getchar()) != EOF)
        if (c >= '0' && c <= '9')
            ++ndigit[c-'0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++nwhite;
        else
            ++nother;

        printf("digits =");
        for (i = 0; i < 10; ++i)
            printf(" %d", ndigit[i]);
        printf(", white space = %d, other = %d\n", nwhite, nother);
}

Nov 21, 2013 at 6:10am
closed account (Dy7SLyTq)
is this from ritchie and kerninghams book? if so this is c and cant remember if its possible in c++ (there is a better c++ way at least) and what it does is in c is a char of range 0-9. in c if you do - '0' then it just becomes an int. ie '9'-'0'=9, '8'-'0'=8, etc. so its just going to cell (the int equivalent of char c) and incrementing by one. in c it is not optional
Nov 21, 2013 at 12:25pm
In the below program, I am curious why the array is indexed as ndigit[c-'0'] rather than just ndigit[c].

In C/C++, all arrays have 0 as the index of their first element. If c is the character '0', then its integer value is greater than 0 (you can look up ASCII code values if you want to know the exact number).

Subtracting the value of '0' from c normalises the integer values of the characters '0' to '9'. This means that c - '0' is 0 when c is '0', and is 1 when c is '1', and so on. If you used ndigit[c] then c would be a number much greater than 9, so ndigit[c] would be past the end of the array.
Last edited on Nov 21, 2013 at 12:27pm
Nov 21, 2013 at 2:47pm
Because the ascii characters '0', '1', '2', ... , '9' are the numbers 48, 49, 50, .... , 57 (see man ascii).

So to index into an array with indexes 0 ... 9 with '0' ... '9' you need to take the 48 off. Or take '0' off.

So:

'0' - '0' = 0
'1' - '0' = 1
'2' - '0' = 2
...
'9' - '0' = 9

So c-'0' is converting the ascii digits ('0'-'9') to their corresponding numbers (0-9), and then using it to index into array ndigit[10].


Topic archived. No new replies allowed.