Search code examples
carrayskernighan-and-ritchie

C Array Count (Beginner)


I'm currently reading 'The C Programming Language' by Kernighan & Richie and I'm struggling to work out what a line does. I think I'm just being a little stupid, and not quite understanding their explanation.

++ndigit[c-'0'];

I've had to change the program ever so slightly as ndigit was previously giving me garbage values, so I just instantiate the array to 0, instead of traversing it with a for loop, and changing the values that way.

#include <stdio.h>

main()
{
    int c, i, nwhite, nother;
    int ndigit[10]= {0};

    nwhite = nother = 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);
}  

Using the program as its input, we get this printed to the console -

digits = 7 2 0 0 0 0 0 0 0 1, white space = 104, other = 291

I understand that 7 2 0 0 0 0 0 0 0 1 is a count of how many times the single numbers appear in the input 0 appears 7 times, 1 appears twice etc.)

But, how does the ...[c-'0']; 'work'?


Solution

  • You asked how the below expression works

     c-'0'
    

    The ASCII code of the entered charecter is subtracted from the ASCII code of 0 and it defines the position in the array where the count has to be stored .

    Suppose you enter 1 from the keyboard ASCII code for 1 is 49 and ASCII code for 0 is 48. hence

       49-48 =1 
    

    and the count will be stored in the array index location 1 .