vendredi 25 juin 2021

Why the "else if" statement wouldn't work and what's the meaning of ndigit[c-'0']?

I'm a beginner to C and I don't understand this example from the book "The C Programming Language by Brian W. Kernighan, Dennis M. Ritchie"

This program counts "each digit from 0 to 9", "white spaces" and "other characters"

#include <stdio.h>

/*count digits, white space, others */
int 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);
}

The output of this program on itself, according to the book, is supposed to be this:

digits = 9 3 0 0 0 0 0 0 0 1, white space = 123, other = 345

but when I run it, it's this:

digits = 9 3 0 0 0 0 0 0 0 1, white space = 2, other = 18

Question 1: Why is there a 0 in ndigit[c-'0']? I don't understand what it does.

Question 2: Why my "else if" and "else" statements wouldn't work properly? They don't get the right numbers.

Aucun commentaire:

Enregistrer un commentaire