Monday 10 January 2011

The C Programming Language (K&R) 01x08—Line Counting (p. 20)—Exercises 1-8

As I make my way through the book “The C Programming Language” by Brian Kernighan and Dennis Ritchie aka K&R, I’m reminded how much time can go into programming a computer. Writing a blog, adds to it, but it’s useful. I’ve already been going back over my entries to remind myself of one thing or another. It is a tool for my use.

I am using Visual C++ 2010 and creating the code as a console application.
 
K&R p. 20, Line Counting

The previous test code counted characters entered at the keyboard by a user. See here. The next step is to count the numbers of lines entered. A line ends with the newline character ‘\n’ (ASCII 10). Hitting enter creates a newline. Counting these lines is straightforward as we simply have to search for the newline character.

Attempt #1 – Count Lines

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

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

int main()
{
     int c, nl;
     nl = 0;

     while ((c = getchar()) != EOF)
           if (c == '\n')
                ++nl;

     printf("%d\n", nl);

     // keep console window open
     system("pause");

     // return some value
     return 0;
} // end main

Note the use of double equal signs in the if condition. If you use a single equal sign in the condition, the program assigns the right side to the left side and your program won’t run correctly. In this instance, it would increment the counter for every character entered. Not what you want.

If the two sides are the same, the condition is true and the line counter is incremented by one. The operator: ++ is the same as writing nl = nl + 1 just shorter.

I can also write: if (c == 10) as the condition and the program runs the same.

If I type in: 1<enter>2<enter>3<enter>4<enter><ctrl>+Z, I get this:


 
Exercise 1-8—Count Tabs, Blanks & Newlines.



Write a program to count blanks, tabs, and newlines.

We have the newline counter above. Need to add variables and if statements to count spaces and tabs.

Here’s the code.

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

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

int main()
{

     int c, nl, nt, ns;
     nl = nt = ns = 0;

     while ((c = getchar()) != EOF)
     {
           if (c == '\n') // ASCII 10 for new line
                ++nl;
           if (c == '\t') // ASCII 9 for tab
                ++nt;
           if (c == ' ') // ASCII 32 for space
                ++ns;
     }

     printf("No. of new lines: %d\n", nl);
     printf("No. of tabs: %d\n", nt);
     printf("No. of spaces: %d\n", ns);

     // keep console window open
     system("pause");

     // return some value
     return 0;
} // end main

Tabs used to indent text.



No comments:

Post a Comment