Sunday 16 January 2011

The C Programming Language (K&R) 01x0D—Counting Diff Chars (p. 24)

I’m only on page 24 of “The C Programming Language” by Brian Kernighan and Dennis Ritchie aka K&R.  That’s just over 10%. That means there’s a long ways to go, but I know I’ve learnt a great deal about the language in a short time.

I thought using the K+R tag for each blog entry would be sufficient to keep track of what I’ve done on this book. Nope. After 12 entries I was loosing track so I created a new page to list the K&R blog entries along with details about what is discussed. Here’s the link.


K&R p. 24

Let us write a program to count the number of occurrences of each digit, of white space characters (blank, tab, newline), and of all other characters.


Sample Code.

I am using Visual C++ 2010 and created the sample code as a console application.

The program is easy because it’s counting each character as entered by the user on the keyboard. Parsing couldn’t be easier. What’s new here is the use of an array, int ndigit[10], to hold the count of each occurrence of a digit (0 to 9). From what I know about C and C++ programmers, they don’t like arrays and don’t use them in the way you would in other languages. But arrays are the current topic of the K&R. More later.

// The standard library includes the system function.
#include <cstdlib>

// C++ standard I/O library.
#include <cstdio>

/* 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);

     // Keep console window open.
     system("pause");

     // Return some value.
     return 0;

} // end main

Output.


No comments:

Post a Comment