Thread: question about K&R example listing 1-6 Arrays

  1. #1
    Registered User fsx's Avatar
    Join Date
    Apr 2009
    Posts
    29

    question about K&R example listing 1-6 Arrays

    Hello everyone, here's the listing:

    Code:
    #include <stdio.h>
    
    /* count digits, white space, others */
    
    int main(void)
    {
    	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) /* recursively print every element in the array */
    		printf(" %d", ndigit[i]);
    	printf(", white space = %d, other = %d\n", nwhite, nother);
    
    	return 0;
    }
    I have some problem understanding the

    Code:
    ++ndigit[c-'0'];
    line, I mean, does it browses sequentially in the ASCII table to seek for the value of c minus the value of the character '0' ?
    If so, how can it find the value for the other digits 1-9?

    Thank you in advance.

    FSX

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by fsx View Post
    does it browses sequentially in the ASCII table to seek for the value of c minus the value of the character '0' ?
    If so, how can it find the value for the other digits 1-9?
    What that means is that it gets an absolute value to correspond to the number. If c is '0' (ascii 48), the array index will be 48-48, so 0. If c is '1' (ascii 49), the array index will be 49-48, so 1. If c is '2' (ascii 50), the index is 50-48=2. Get it? The ndigit array keeps a count for each number, 0-9.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Just a quick question about character arrays
    By Welshy in forum C Programming
    Replies: 3
    Last Post: 04-03-2006, 07:20 AM
  2. K&R question
    By tcpl in forum C Programming
    Replies: 2
    Last Post: 02-26-2006, 09:19 PM
  3. newb question on ARRAYS
    By viciousv322 in forum C++ Programming
    Replies: 18
    Last Post: 11-16-2005, 07:34 PM
  4. A question concerning character arrays
    By ellipses in forum C Programming
    Replies: 3
    Last Post: 03-08-2005, 08:24 PM
  5. Question about arrays?? PLease read..
    By foofoo in forum C Programming
    Replies: 3
    Last Post: 06-24-2002, 02:40 PM