HOME - - - - - - - - - Other material for programmers - - - - - - - - - Pascalite Tutorial Table of Contents

Pascal Programming: A Little Counting in Binary

This version of this tutorial is fine tuned for the open source FPC, aka Free Pascal. Most of what you read here should also directly apply if you are using Borland's Turbo Pascal (TP hereafter). It is also available for free. Please send me an email with "complaints" if something doesn't work!

If you have a Pascalite, or the software emulation, then there's a separate tutorial for you, covering much of the ground as presented here for the FPC/ TP crowd.


Have you felt that some of the tutorials to date took things a bit easy? Not enough "meat" to "chew" on? Fear not! This tutorial has lots for you to struggle with...

We do more with "Repeat... Until" loops, we nest them, we meet "Val", "Random", "Randomize".. all fairly simple things... and then we go on and meet the very powerful "For... (some variable):=(something) to (something) do..." loop creator. That is an important concept. Happily, we're only having a simple "first meeting" here.

Enjoy!....

One view of programming says that it is all about three simple things:

In our programs to date our input has gone in via the keyboard. The program "asks" for our input when it gets to a readln line. It stores what we say in a variable.

Following the dictates of the instructions provided by the programmer, the computer "digests" the inputs. This is the "processing" element, and it leads to....

Some kind of message being PUT OUT from the computer. This is the output. The place that message will go will, for us, be the computer's screen. People following the Pascalite variant of these tutorials can write programs which sent their output either to a rather small, limited, screen, or to some LEDs. Turning an LED on (or off) is "output" just as much as words or numbers on a screen are "output". The printer is another commonly used medium for output. With a little more work, the program's output can affect a wide range of actuators, from audio speakers to motors to... (there are lots of ways to do output!)

In these introductory chapters of this my Pascal tutorial, we will only output things to the screen. Learning enough to have your computer turn LEDs on and off is not difficult... it just requires that you have a PC available which you could bear damaging in your early days as an electronics engineer!

Sticking (mostly) with the familiar, enter the following program, enter what follows, and try running it, even though it is pretty pointless so far!
program Fifth;
uses crt;

var bDataIn, bErrCode:byte;
    sTmp,sDataOut:string;

begin
ClrScr;

repeat
  writeln('Enter a number, 0-7, or, to quit, 99');

  repeat //**1
    readln(sTmp);
    val(sTmp, bDataIn, bErrCode);
  until bErrCode=0;//**2

until bDataIn=99;

writeln;//Causes a blank line in the output.
writeln('Bye.');
writeln('Press the "Enter" key to end the program.');
readln;
end.

I hope that most of that made "sense"... of a sort? I hope you could see what would happen, even though why you'd want such a program is probably still obscure.

Let's talk in detail about the material between the inner "repeat" (at //**1) and it's "until" (at //**2)

readln(sTmp) should not perplex you. It just fetches whatever you type (the input), and stores it in the variable sTmp. Because sTmp is a string type variable, you can type anything, without problems.

However, for what I want this program to do, a number is necessary. "val" is a reserved word. It is built into FPC. After "val" (for "value"), there will always be 3 parameters, in brackets.

The first will "deliver" a string to val. If I type the string "123", to you and me it looks just like the number 123. The computer isn't that "clever". Val takes what's in the string, sTmp in the case of our program, and attempts to turn it into a number. If sTmp had been storing "123" when Val was called, Val would succeed, and it would put the number 123 into the variable bDataIn. (It uses whatever variable is supplied as the second "thing" (parameter) after the Val.)

The third parameter would be filled with 0 if sTmp was "123". If Val has not been able to convert the string into a number, it will put a non-zero number into the third parameter, bErrCode in this case.

Run the program. Try entering some numbers (other than 99) and some non-numbers. I hope that you now see what the program is doing. If you enter a non-number, you have to supply a new datum. You are "stuck" inside that inner loop until you supply a number.

Okay... now supply "99". The program should exit, after you press enter to acknowledge the "Bye" (program ending warning message). (That "99" is a "rogue value", by the way. In a moment, we're going to do "interesting" things with numbers entered by users... but "99" will be taken as a "special code", not treated as just another number. It will continue to stand for "end program now." Such things are called rogue values.)

Onward! Let's make the program do something with the number. We've seen "input", and we've seen "processing" (well, the effect of processing)... but the "output" has been pretty uninspired so far!

Take another small step forward by modifying the program by adding the 3 lines marked with //**s. (Small steps work well... when something goes wrong, you don't have far to search for a culprit.)

program Fifth;
uses crt;

var bDataIn, bErrCode:byte;
    sTmp,sDataOut:string;

begin
ClrScr;

repeat
  writeln('Enter a number, 0-7, or, to quit, 99');
 repeat //**
  repeat
    readln(sTmp);
    val(sTmp, bDataIn, bErrCode);
  until bErrCode=0;
 until (bDataIn<8) or (bDataIn=99);//**
writeln('Something good goes here in a moment.');//**
until bDataIn=99;
writeln;
writeln('Bye.');
writeln('Press the "Enter" key to end the program.');
readln;
end.

Now, in place of the one line....

writeln('Something good goes here in a moment.');//**

... insert...

if bDataIn=0 then writeln('In binary, that would be: 000');
if bDataIn=1 then writeln('In binary, that would be: 001');
if bDataIn=2 then writeln('In binary, that would be: 010');
if bDataIn=3 then writeln('In binary, that would be: 011');
if bDataIn=4 then writeln('In binary, that would be: 100');
if bDataIn=5 then writeln('In binary, that would be: 101');
if bDataIn=6 then writeln('In binary, that would be: 110');
if bDataIn=7 then writeln('In binary, that would be: 111');

(Remember that you can copy things from here, and used Edit|Paste From Windows within FPC.)

Yes... there are more clever ways to achieve the result... but we'll come to then. Be it ever so crude, we now have a program which will tell you the binary form of any number from zero to seven. You INPUT a number, the program PROCESSES it, and you get the binary equivalent OUTPUT.

This tutorial was adapted from one for the Pascalite. The Pascalite has some hardware that made it possible to write a more fun program for it, but what we have here for the FPC and TP Pascal compilers is just as educational as what was done with the Pascalite.

Did you notice the new data type you encountered, "byte"? Byte-type variables can hold the whole numbers from 0-255 (inclusive.) They aren't very clever... but then, we didn't need anything clever here, did we?

Actually, that little bit of "cleverness" wasn't clever. Val is capable of converting, say, the string "345" into the number 345... but a byte-type variable can't store it. If you enter 345 into the program as it now stands, you'll see it come to a crashing halt when Val tries to put 345 into bTmp. You get a cryptic error message.

The right way to fix this would be to go back and change every reference to bDataOut to iDataOut, and declare it as an integer.

A messy "quick fix" would be to make the inner Repeat... Until do....

    readln(sTmp);
    bErrCode:=1;
    if length(sTmp)<3 then val(sTmp, bDataIn, bErrCode);

Notice that we added the bErrCode:=1; line? That became necessary because we will now not necessarily be executing the val statement, will we? And that could give rise to encountering "until bErrCode=0" before any value has been assigned to bErrCode... Not allowed! So we initialize the variable, just in case.

That brings us to the end of the heart of this tutorial. There are two other things to deal with in a moment, but take a moment to catch your breath here.




Once again, we're about to encounter something that was more fun on the Pascalite. With that, we could wink LEDs in pretty patterns. With FPC and TP, you can do much, much more... but for the moment they'll look dull. Sorry.

Revise (or replace) the program we had to make it...

program Fifth;
uses crt;

var bDataIn, bErrCode, bCount:byte;
    sTmp,sDataOut:string;

begin
ClrScr;
bCount:=0;
randomize;
repeat
  bCount:=bCount+1;
  bDataIn:=random(4);
  if bDataIn=0 then writeln('In binary, that would be: 000');
  if bDataIn=1 then writeln('In binary, that would be: 001');
  if bDataIn=2 then writeln('In binary, that would be: 010');
  if bDataIn=3 then writeln('In binary, that would be: 011');
  if bDataIn=4 then writeln('In binary, that would be: 100');
  if bDataIn=5 then writeln('In binary, that would be: 101');
  if bDataIn=6 then writeln('In binary, that would be: 110');
  if bDataIn=7 then writeln('In binary, that would be: 111');
  writeln('Press the Enter key');
  readln;
until bCount=12;
writeln;
writeln('Bye.');
writeln('Press the "Enter" key to end the program.');
readln;
end.

What we have is much like our earlier program. However, now instead of a human supplying numbers, the computer is doing it. We've also changed the program so that it does 12 numbers and then stops... the rogue value mechanism has been taken out. Because humans aren't inputting things, we can take out a bunch of tests.

The "random" "thing" is new. What happens when you say bDataIn:=random(8) is that the computer picks a number for you, as if it has thrown dice. The number it returns could be a zero, or anything up to a seven, inclusive. It won't be an 8. If you wanted 0- 15, inclusive, you'd say random(16).

Notice the line saying "randomize"? You have to execute "randomize" once, and preferably only once, as here, to get different random numbers each time you run the program. (Yes, I realize that Pascal's idea of "random" isn't quite what most people mean by "random".... but it does very nicely for many things.




One last thing... not small, I'm afraid... don't skip this next stuff!

Redo the program again. Make it....

program Fifth;
uses crt;

var bDataIn, bErrCode:byte;
    sTmp,sDataOut:string;

begin
ClrScr;
randomize;
for bDataIn:=0 to 7 do begin
  if bDataIn=0 then writeln('In binary, that would be: 000');
  if bDataIn=1 then writeln('In binary, that would be: 001');
  if bDataIn=2 then writeln('In binary, that would be: 010');
  if bDataIn=3 then writeln('In binary, that would be: 011');
  if bDataIn=4 then writeln('In binary, that would be: 100');
  if bDataIn=5 then writeln('In binary, that would be: 101');
  if bDataIn=6 then writeln('In binary, that would be: 110');
  if bDataIn=7 then writeln('In binary, that would be: 111');
  writeln('Press the Enter key');
  readln;
  end;//for loop
writeln;
writeln('Bye.');
writeln('Press the "Enter" key to end the program.');
readln;
end.

This program is even simpler than the last. Of course it isn't as "clever", now, either. All it does is show you the binary for 0,1,2,3,4,5,6... and!... 7.

Notice that we've got rid of the bCount variable.

More particularly notice that we've replaced the "Repeat... Until" with a terribly important loop creator, the "For" statement. The reserved words "for" and "to" and "do" are all part of it.

The "For" statement starts off by putting a value in a variable, 0 in bDataIn in this case. It then, for the moment, skips over the "to 7" bit. The word "Do" always appears where you see it. The "For" then causes whatever comes next to happen. In this case "whatever comes next" is quite a lot... everything from the "Begin" down to the "End; //For". Remember compound statements? The "Begin... End" "glue" all this simple statements together, making what, as far as the "For" is concerned, just "one" (big) statement.

When the "one big statement" has been executed once, the computer goes back to the start of the For line. It remembers that the line has already been done, and "looks" in the bDataIn variable. It adds 1 to whatever it finds. At the moment, it would find a 0, so after adding one, there's a one. That is put back into the bDataIn variable. Next the computer looks at the "to 7" part of the "For" statement. It compares the contents of bDataIn to the 7. As bDataIn is not yet larger than 7, the whole thing repeats... the "one big statement" is executed again, and the computer goes back to the start of the "For" line.

This is repeated again and again... but eventually, the number in bDataIn is bigger than 7. At this point, the computer skips over the "one big statement, and goes on to do whatever comes after it. And from there it just carries on.

The repeat... until loop has its uses. But the "For" loop probably gets used more.

If that wasn't 100% clear, don't worry... you'll meet the "For" loop many more times!




Enough for now, I trust? There's always the index of Pascal tutorials when you're raring for more.


Please also note that I have two other sites, and that the following search will not include them. They have their own search buttons.

My Sheepdog Guides site.
My Arunet site.

Go to the sites above, and use their search buttons if you want to search them.
To search this site....

Search this site or the web powered by FreeFind

Site search Web search
The search engine merely looks for the words you type, so....
*    Spell them properly.
*    Don't bother with "How do I get rich?" That will merely return pages with "how", "do", "I"....

You can also search this site without using forms.
Ad from page's editor: Yes.. I do enjoy compiling these things for you... hope they are helpful. However.. this doesn't pay my bills!!! If you find this stuff useful, (and you run an MS-DOS or Windows PC) please visit my freeware and shareware page, download something, and circulate it for me? Links on your page to this page would also be appreciated!
Click here to visit editor's freeware, shareware page.


Want a site hosted, or email? You can also help me if you sign up via this link to 1&1's services. (I wouldn't recommend them unless I was happy after several years as one of their customers. The Google advertisers pay me. I know nothing about them or their services, of course.)



Valid HTML 4.01 Transitional Page has been tested for compliance with INDUSTRY (not MS-only) standards, using the free, publicly accessible validator at validator.w3.org. Mostly passes.

AND passes... Valid CSS!


Why does this page cause a script to run? Because of the Google panels, and the code for the search button. Also, I have some of my pages' traffic monitored for me by eXTReMe tracker. They offer a free tracker. If you want to try one, check out their site. Why do I mention the script? Be sure you know all you need to about spyware.
Editor's Main Homepage
How to email or write this page's editor, Tom Boyd

....... P a g e . . . E n d s .....