Stuck? Need help? Ask questions on our forums.
*/
*/

Counting Lines

Theme Graphic
Theme Graphic

Software Tools in Turbo Pascal

I intend to go through SOFTWARE TOOLS IN PASCAL by Kernighan & Plauger and to re-write the programs they presented using Turbo Pascal, taking advantage of Turbo Pascal's improvements over the...

Subscribe

Author

Archive

Tags

Posted on Monday, October 22, 2007 at 5:50 PM

Counting Lines

The next program counts the number of lines in a text file. My version takes advantage of the fact that ReadLn without a parameter list will move the file pointer past the next CR,LF (new line). Thus the program does not even have to know about the intervening chars. The result is a shorter and more elegant program.
Program LineCnt ;
{
      count lines in standard input
}
Var
   Count : LongInt ;
begin { LineCnt }
   Count := 0 ;	
   while NOT eof do begin
      ReadLn ;
      Count := Count + 1
   end ;
   WriteLn (Count:0)
end.  { LineCnt }
I declare Count as a LongInt, a type that K&P did not have access to. I also used LongInt as the counter in CharCnt. It allows the programs to work with much larger files.

As an interesting exercise try omitting the line
Count := 0
which initializes the counter. This should be a bug but I discovered long ago that the programs still work. It apparently is an undocumented feature of Turbo Pascal that integers get initialized to zero by default. Now that I know about it I try never to use it. It goes against the spirit of defensive coding.

Tags: initialize, default Views:171

0 comments on "Counting Lines"
No comments posted yet.

Leave A Comment
Subject:


Comment:
   Bold Italic Underline          Code Link Image Horizontal Rule


Because you do not have or are not logged in to your Programmer's Heaven account, please enter your name.

Name:


To help prevent comment SPAM, please enter the magic code '211' in the box:




Posting Rules
Please follow these rules when posting comments on blog posts.
  • Do not post anything that is racist, hate speech or of a sexual or adult nature.
  • Do not post or link to anything that infringes copyrighted laws.
  • Posting about security or legal topics is fine so long as you are not glorifying or encouraging people to perform illegal activities.
  • Both the author of this blog and the Programmer's Heaven administrators may delete any inappropriate comments without notice at their own discretion.

corner
© 1996-2008 CommunityHeaven LLC. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
North American business development: Nicolai Wadstrom. Publisher: Lars Hagelin.
Resource Listings