Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

++ndigit[c - '0'];

Name: Anonymous 2012-09-11 14:05

So, I'm workin on the book "The C Programming Language" when this code comes up under the chapter for character arrays:


#include <stdio.h>
/* count digits, white space, others */
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);
        getchar();
}


It all makes sense, expect for the "++ndigit[c - '0'];" in line 14. I don't understand what this is doing, or why it has to do it. Shouldn't the program run the same if you didn't add the " - '0'" part? But when I take out that part, the program will compile, but it will return all '0' for every number, even if they are present.

So what exactly does subtracting '0' do for this program?

Name: Anonymous 2012-09-11 21:29

>>7
No. With a for loop, the first statement (i = 0) is executed, then the expression (i < j) is evaluated, then the loop is executed, then the last statement (++i) is executed. Then it goes back to evaluating the expression and starts again.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List