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-12 2:18

>>11
for: init while: test do: body and: incr = (
init value.
^[body value. incr value. test value.] whileTrue.
)

|i| for: [i::0] while: [i<10] do: [Transcript show: i printString] and: [i::i+1].

(*prints 123456789*)

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