Pascal Tutor


Home

About the Author

General Programming

Pascal

Delphi

C&C++

Visual Basic

SQL

JAVA Script

Links

 

[ Pascal Tutor ] Pascal Graphics ] Pascal Math ] Pascal Misc ]

Start your Borland Pascal 7.0 first. Feel it. Type some words then delete it. Once you will get used to it. Let's begin our lesson !

Pascal is a structured programming language. It means that everything you program, must be structured and in orderly. No more free gotos and jumps.

It has a format. Yeah... right. You don't have to obey it anyway since you COULD extend it to complex ones.

A format of very simple Pascal programs :

uses ....

var
...
begin
.... (Your program is here)
end.

The word "end" here should end with stop ("."). Every Pascal program blocks begins with the word "begin" and ends with the word "end". Some of the "end" word ends with ";" or "." or just nothing. That will be described later (not in this lesson).

Writing

For example :
Type in these words in your BP, and run it by pressing Ctrl+F9

begin
   Writeln('Hello, World !');
end.

In this case we don't need the word "uses" and "var". Try to run it. It should display "Hello, World !" on screen. But perhaps it's too fast. But, how can I view it anyway ? Press Alt+F5.

What is the word "uses" for ? It's a kind of terms to declare that we use specific library. Some are standard ones. At first, we use the standard ones that come with every Pascal compiler.

The one we will use most is crt unit, since it contains various commands that is suitable for us for this moment.

What is "Writeln" for ? Writeln is a command to write something into the screen. If you want to write a sentence, just wrap it with quote ('). And don't forget the pair of brackets and the semicolon. Example :

begin
   Writeln('I learn Pascal');
   Writeln('Hi, there !');
end.

You will see another messages on screen. View it with Alt+F5 after running
it by pressing Ctrl+F9.

So, you want to clear the screen when the program starts. You need to add the word "Clrscr;" just after the word begin. But it needs "uses crt" since Clrscr is one of the commands included in crt library. (Pascal terms for library is unit) So, the above example would become :

uses crt;

begin
   Clrscr;
   Writeln('I learn Pascal');
   Writeln('Hi, there !');
end.

Pascal has a command "Write" instead of "Writeln". Why don't you just try that ? Just replace all the "Writeln" into "Write" (of the program above). Run it and see what happens. See the difference ?

It'll output "I learn PascalHi, there !". Stick !

Sometime, we need to leave a line blank. Suppose we want a blank line bet- ween "I learn Pascal" and "Hi, there !". Just insert "Writeln;" between, and bingo ! Try inserting the Writeln in correct order so it yields :

I learn Pascal

Hi, there !

If you do have a good grip about how to write something on screen, please proceed. Otherwise, you should repeat it once again.

Now the input parts.

When we ask computer to receive input from users, we need something to store the input before it is being processed. That was variable. We need it to corporate our program. There are various types of variable and with var- ious range too. Here are some frequently used variable types :

Type name Range Type
Shortint

-128 to +127

integer
Byte

0 to 255

integer
Integer

-32768 to +32767

integer
Word

0 to 65535

integer
Longint

-2146473648 to +2146473647

integer
Real

2,9x10^-39 to 1,7x10^38

fractional
String

up to 255 letters

non-numeric
Char

1 letter only

non-numeric

^ indicates to the power of, ex. 2^2 is the same as 2² wich is the same as 4

There are many more, but that's all we need for now.

How to declare our variables ?

As we seen in our format previously that we have "var" section there. That's where we suppose to declare our variables.
Here is some example :

var
   MyAge : Byte;
   Comments : String;

To assign variables with values, you need to write this syntax :
var_name := value;
This should be written anywhere within begin ... end block, in appropriate location.

Example :

var
   MyAge : Byte;
   Comments : String;
begin
   MyAge:=19;
   Comments:='Hi, there ! I'm learning Pascal';
   Writeln('I am ',MyAge,' years old');
   Writeln(Comments);
end.

Write it down, run it an view it on screen !

How to get the user's input ? Yeah, that's easy actually. Similar to Write or Writeln, Pascal uses Read and Readln. The difference is that in Read or Readln, we cannot write anything on screen but to get user's input.

Example :

var
   MyAge : Byte;
   Comments : String;
begin
   Write('How old are you ? '); Readln(MyAge);
   Write('Give us comments: '); Readln(Comments);
   Writeln;
   Writeln('I am ',MyAge,' years old');
   Writeln(Comments);
end.

Write it down, run it an view it on screen !

Now, you know how to get user's input. But wait ! If I enter 23.5 in 'How old are you ?' it spouts error ! Yeah, you right ! The value on that question is actually stored in MyAge variable. MyAge variable is a Byte variable. So it only accept integer values between 0 to 255. That's the range of it ! It cannot go further. If you want computer to accept fractional values
in MyAge, try using Real instead of Byte.

But why when I change it to Real, it outputs erratical numbers ? No, it actually doesn't throw garbage on the screen. It just exponential numbers.For ordinary people -- non technical -- it would be more convenient to view fractional number at 3 or 4 place after the decimal point. Try changing :

Writeln('I am ',MyAge,' years old');

to :

Writeln('I am ',MyAge:2:4,' years old');

What does it mean ? Why some ":2:4" attached to MyAge ? For real numbers, it means : Show 2 place before decimal point and 4 place after decimal point So, when we enter 23.5 for MyAge, it will output :

I am 23.5000 years old

Try changing ':2:4' with other values. Be creative !

Can we apply it to the string ? Nope ! But it only accepts just ":x". It means that "I only grant this variable x place on the screen to express its value". Suppose you change :

Writeln(Comments);

to

Writeln(Comments:5);

Try writing long commnts when the program is running. See what happens. If you enter "Programming" as the Comment, you will see output :

Progr

Ok ! I'm tired of pressing Alt+F5 to view this tiresome tutorial result !
No problema. Just add "Readln;" just before "end." Try it yourself !

Now, let's extend our first program with a "little variation".

Crt unit does not consist of Clrscr only. It has a lot of interesting functions and procedures.

OK ! Let's give color to our text on screen ! We use Crt unit's procedures:
TextColor and TextBackGround. Both accepts value ranging 0 to 15. Example :

TextColor(14);
TextBackground(1);

It will set the foreground color to yellow and blue background for the next
Write or Writeln. Yep ! Easy ! Let's look at full example :

uses crt;

begin
   TextColor(14);
   TextBackGround(1);
   Writeln('Hello there !');
end.

Run it and see what happens.

O ho ! That's great ! Yellow over Blue. Try to figure all color values ! A lot of variation could be applied and it's all yours to choose.

There's even more convenient than above : Use TextAttr instead. It's a kind of a "combo" variable. You just assign a value that is :
(background * 16)+foreground

Suppose you want a cyan background (or light blue), the number is 3, and black foreground, that is 0. So you would write this :

TextAttr:=(3*16)+0;

Then, subsequent writes on screen will be in black over cyan. Easy, eh ?

If you clear screen AFTER you assign colors, you will found that the entire screen will be wiped to the last assigned color. Suppose you have set color black over cyan, if you clear the screen, the entire screen will be black over cyan ! It's useful if you want alternative background instead of black -- It's boring. Yeah ! Easy !

Want to have big characters on screen ? Try adding "TextMode(CO40);". Well, TextMode is used for changing text mode. Valid values to pass is CO80, that is for return back to normal mode, or LastMode -- that is back to last mode visited, and refer help for more ! Example :

uses crt;

begin
   TextMode(CO40);
   Writeln('A Real BIG Characters on screen !');
   Readln;
   TextMode(CO80);
   Writeln('Back to normal');
   Readln;
end.

Before we continue, I would like to introduce the screen behavior of PCs in text mode. Screen has a resolution. In text mode, screen has either 80 or 40 horizontal resolution (generally) and 25 vertical resolution. It means, the screen could be 80 cols by 25 lines or 40 cols by 25 lines. The setting of TextMode reflects to this : CO40 -- sets the screen to 40 chracters wide and 25 lines -- and CO80 -- sets the screen to 80 characters wide and 25 lines too. 40 characters wide causes the screen to "stretch" horizontally, so in result, WIDE characters appear on screen. EGA and VGA has a special feature that is also supported by crt unit : an enhanced text mode consists of 43 (when EGA) or 50 lines, instead of 25. We put the value "Font8x8" inside TextMode parameter.

We can also directs our text output at specified location by using GotoXY. It accepts parameters X and Y (both are bytes). Note that X reflects to column position, and Y reflects to line position. Both X and Y must not exceed the range of the current text mode.

Now, let' s play with sounds ! It's easy ! Start playing the sound with Sound, delay for several times, then NoSound. Let's practice !

Cut and paste this program. Run it in BP.

uses crt;

begin
   Sound(440); Delay(100); NoSound;
   Sound(550); Delay(100); NoSound;
end

Sound accepts frequency number and it's a word. It is the value of frequency you want to play. Delay accepts value of words. It reflects how many milliseconds (1/100th of a second) you want to delay. NoSound tells the PC to stop playing the note. If you omit Delay, you may not hear any voices. Try it and figure it out !

Pascal is able to calculate things and it made programming much easier. OK guys, here is the convention :

Addition (+), Subtraction(-), and Multiplication(*) :
If both numbers are integers, it yields an integer result. Otherwise, even there's only one is real, the result becomes real.
integer with integer = integer
integer with real = real
real with real = real

Division(/) :
It always yields real result.

Special Division(Div) :
It's quite the same as (/), but it always yields integer result.

Fine, fine. But how can I apply this ?

Real life equation Becomes
y = 5 x 3 y:=5*3; (y is either integer or real)
z = 5 + 4 x 3 z:=5+4*3; (z is either integer or real)
a = 3.14 x 7 x 7 a:=3.14*7*7; (a is always real)
b = 14 x (5 + a) b:=14*(5+a); (b depends on a, if a real, b is always real. If a integer, b may be real or integer).

Yeah, that's quite an example. But you should know it though. How about the special division :

a:=22/7; when a is real, it yields result 3.142856 .... so on otherwise, error.
b:=22 div 7; b is always integer, and it hold 3. Div always round to the floor, I mean not to the top nor not to the nearest integer.

Even 98 div 3 will result 32 though normal people consider 32.66666666.....
to 33.

Pascal could convert the real numbers to integers using Trunc and Round.

Trunc behaves similarly like Div, it rounds to the floor always. Round is more moderate though, it rounds to the nearest integer. Evaluate the expressions below and see the result;

uses crt;

begin
   Clrscr;
   Writeln(Trunc(12.31));
   Writeln(Round(12.31));
   Writeln(Trunc(31.49));
   Writeln(Round(31.49));
   Writeln(Trunc(44.59));
   Writeln(Round(44.59));
   Readln;
end;

Conditional branching

What is conditional branching anyway ? Well, it's a if not this, do this, else do that ... ummm similar things like that, you know. We have the conditions, and if the conditions are satisfied, do some statements, otherwise do something else.

Pascal provides two ways to implement conditional branching. One uses if,
the other uses case ... of.

Well, let's discuss the first part : if

The structure of "if" in Pascal is like this :

if condition then
begin
:
:
end;

OR, if you add the "else" part :

if condition then
begin
:
:
end <-- notice that the semicolon disappeared now !
else
begin
:
:
end;

Now, you ask : How could Pascal determine the process ? If the condition(s) beside the word "if" is met, then the block begin...end -- just below the if -- will be executed, otherwise, then the block begin.. end after the else will be executed. If we have the if structure as the first one -- that is, no else block -- the program execution will continue
after the word "end". Let us examine the excerpt of the code below :

if counter<10 then
 begin
    counter:=counter+1;
    writeln(counter);
 end;
writeln('Done');

If the variable "counter" has the value less than 10, the commands between begin and end will be executed. If it has the value 10 or more, it skips the process just after the end. It means that it does the writeln('Done');.
But, don't be mistaken. Even the counter has the value less than 10, after it has done the commands between begin and end, it continues the process to the next statement -- that is writeln('Done');.

Nested if

Now how to have some ifs inside an if ? Yeah, right ! That's perfectly legal provided if you don't forget to wrap the begin..end (if there are twoor more statements inside). Here is one example :


if i<10 then
 begin
    writeln('i is more than 10.');
    if j>3 then writeln('j is more than 3.');
 end;

Yes, yes ! You may do if inside the begin..end block after the else too. Why don't you do some experiments ?

Combining the conditions

Pascal lets us combine the conditions. Say that if a salesman is qualified to get the project if he has sold 7000 pieces of products and he has at least 3 years of experience. This is the example :

if (productsold>=7000) and (experienceyear>=3) then qualified;

Yes, this cannot be run of course. In this example I would like to introduce the "and", "or", and "xor" keywords.

The keyword "and" means that it will return "true" if both conditions are met. It means that the first begin..end block will be executed only if both conditions are true.

The keyword "or" means that if there is at least one of the conditions is met (or both), then the first begin..end block will be executed.

The keyword "xor" means that if there is ONLY one condition is met (notboth), the first begin..end block will be executed.

The keyword "not" means negating all conditions. Then if the condition is true, it will be considered false and vice versa.

Case..of

Sometimes, you really need to select conditions according some criteria. You're clever ! Use some ifs and let it be done ! But how if the criterium was quite long and complex ? I'm sure that it would be a daunting task to
have an if for each. How could we categorize the criteria with some similarities and simplify the problem.

Suppose we have to do the grading system for our campus. Say, if the student has 80 or more deserves an A. 70 to 79 is for B, 60 to 69 is C, 50 to 59 is D, and 49 or below is E. The if example would be like this :

(Note that mark is a byte)

if mark>=80 then
   grade:='A'
else { 79 or below goes here }
if mark>=70 then
   grade:='B'
else { 69 or below goes here }
if mark>=60 then
   grade:='C'
else { 59 or below goes here }
if mark>=50 then
   grade:='D'
else { 49 or below goes here }
   grade:='E';

Wow, that's pretty long. Now see this :

case mark of
   80..100:  grade:='A';
   70..79:   grade:='B';
   60..69:   grade:='C';
   50..59:   grade:='D';
else grade:='E';
end;

Simple and elegant ! Now, let's learn about readkey statement. It is one of the commands included in crt unit, like clrscr. What it does ? It receives the ASCII code of pressed keyboard button. Well, what is ASCII code anyway? It is some sort of codes that is defined for computers. If we pressed the keyboard, it produces some sort of code, and then the computer translates it into the ASCII code, the code we commonly (programmers) know.

(Note for advanced programmers :
Don't laugh at this, I have to explain what ASCII code exactly to the non programmer folks in a practical and easy way without going into the complicated talks ! Yes, we know the "origin" keyboard codes. I do too.)

Readkey is a function, returning a char value. OK, let's see how it works !

program test_readkey;
uses crt;

var
   c : char;

begin
   c:=readkey;
   case c of
     #8 : writeln('You presses backspace');
     #9 : writeln('You presses tab');
     #13: writeln('You presses enter');
     #27: writeln('You presses escape');
     #32: writeln('You presses space');
     else writeln('You presses other key');
   end;
end.

The program simply waits for a keypress then detects it and quits.

Now you asked : Why do we use the # sign ? Because it denotes a character with a code. Suppose #8 means a character with a code of 8. Why don't we use the .. like the previous example ? Because in this case we don't speci-
fy ranges of values while the first example did. Like 80..100 means from 80 to 100.

Let us detect the arrow keys. Arrow keys, just like function keys, are extended. It means it generates a special codes. Now, here is the code to trap them :

program trap_arrow;
uses crt;

var
   c : char;

begin
   c:=readkey;
   if c=#0 then { If extended codes, }
    begin
      c:=readkey; { read the code once more }
      case c of
         #72: writeln('Up arrow');
         #75: writeln('Left arrow');
         #77: writeln('Right arrow');
         #80: writeln('Down arrow');
      end;
    end;
end.

How to detect the ASCII number ? How do you know that ? Easy, with ord. Suppose you want to know the ASCII codes for each keyboard keys. Do this :

program trap_key;
uses crt;

var
   c : char;

begin
   c:=#0;
   while c<>#27 do
    begin
      c:=readkey;
      if c=#0 then { If extended codes, }
       begin
         c:=readkey; { read the code once more }
         writeln('Extended : ',ord(c));
       end
      else writeln(ord(c));
    end;
end.

Now, press keyboard keys, and see the codes. Combine it with Ctrl, Alt, and Shift and see what happens. To understand the program above, you need to know what while means. The statements inside the while will be repeated on
and on as long as the condition (c<>#27) is met. It means the c:= readkey; if c=#0 ... will be repeated as long as c is not equal to character 27. Since character 27 is escape, then the program simply runs until user pres-
ses Esc.

Constant

In real world, we meet many constants, such as ã = 3.1415926513... or e = 2.7182818284529... Many of these are impractical number so that it is quite hard for us to remember, at least for some of us. Pascal has a good facility to use the constants. Even it has predefined ones, like pi (ã).

How to define our own constant ? Easy, just like a variable definition, we just give "const" above our constants AND start tayloring our needs.

const
:
myconst = 1234;
:
:
(Like variable definition)

We just omit the constant type, Pascal will understand it. We can use it just like a normal variable. Example :

const
   myconst = 1234;

var
   i : word;

begin
   i:=40;
   writeln(i*myconst);
end.

Easy, no ?
But heed my word, constants is unchangeable. If you try to change it, Pascal will say error.

Wait a minute ! I heard that Pascal's constants can be changed somewhere in the program. You are absolutely right ! Now, the declaration becomes :

const
   myconst : mytype = thevalue;

example:
const
   abc : word = 1234;

You may not declare constants with values exceeding the type, like :
const
   aaa : word = 100000; { Illegal because word is integer ranging 0-65535 }
   bbb : byte = 123.44; { Illegal because of the fractional part }
   ccc : string = 123; { Illegal because incompatible type }

Clear ? How can we modify them inside our program ?

const
   myconst : word = 1234;

var
   i : word;

begin
   i:=40; myconst:=1000;
   writeln(i*myconst);
end.

Easy, just like a normal variable, doesn't it ?

Loop

In many cases in programming, we need to repeat processes. In that case, we need some loops. Pascal understands it, therefore it provides three types of loops :

For ... to ... do
While ... do
Repeat ... until

Well, let's look inside them :

For ... to ... do
Syntax :

For variable := fromwhat to what do
begin
:
:
statements / commands
:
:
end;

Example :
{ Suppose i is an integer }

For i:=1 to 5 do
begin
   writeln(i);
   if i=5 then writeln('Finished !');
end;

It yields 1, 2, 3, 4, 5, then the message 'Finished !'. You see that inside the begin-end block, you could add any commands you want. If there is only one command inside it, you may omit the begin-end, just like "if" we have studied before. Suppose you omit the 'if i=5 ...', so inside the begin-end we have only 'writeln(i);'. We can omit the begin-end, then it becomes :

For i:=1 to 5 do
writeln(i);

If we want to count backwards, i.e. from 5 to 1, we just change 'to' into 'downto', so check this out :

For i:=5 downto 1 do
writeln(i);

How about if we want to step more than one, i.e. 1, 3, 5, 7, 9, ...? BASIC provides the 'STEP' how about Pascal ? Well, in this case, Pascal DOES NOT provides such, but if you are creative, you are able to do it. This applies to fractional step as well. BUT, Pascal does include special feature. Check this :

{ Suppose c is a char variable }

For c:='A' to 'Z' do write(c,' ');

You may also write "For c:='Z' downto 'A' do write(c,' ');". You may even
write this : (Suppose b is a boolean)

For b:=false to true do writeln(b);

And many even 'stranger cases' than this, if you have studied 'type' statement.

While...do
Well, if you have learned BASIC, you will find that While...do is quite the same as "WHILE ... WEND". The syntax is :

While conditions do
begin
:
(statements / commands)
:
end;

Before we enter the begin-end block, FIRSTLY it checks whether the condition(s) are satisfied. If not, it just skips it out, or else it does any commands inside begin-end. When it reaches the end, it checks the condition again. If it is satisfied, then loop again. If not, go out. It goes on and on.

For example :

i:=1;
While i<6 do
begin
   writeln(i);
   i:=i+1;
end;

You may also combine conditions with AND, OR, or XOR. If Pascal does not provide 'STEP' like BASIC, you can change the 'for' into 'while' that has a lot more flexibilities.

3. Repeat ... Until.
The syntax is :

Repeat
:
statements / commands
:
Until condition;

Unlike While...do, Repeat...Until does not check for conditions at first. It just enters the block and do anything inside. Beware that Repeat...Until does not require begin...end. AT THE END, it then checks whether the conditions are satisfied or not. If SO, it QUITs. That is the third difference from the While...do. If it does not, it simply loops back.

For example :

(uses crt first)
Repeat Until Keypressed;

i:=1;
Repeat
   writeln(i);
   i:=i+1;
Until i>5;

In 'While...do' and 'Repeat...until' there is a chance to get an infinite loop. Simply give an impossible conditions. But remember, that this also a drawback if we don't use it carefully. Example :

While 2<4 do OR Repeat
begin
(bla bla bla ...)
(bla bla bla ...)
end; OR Until 3>5;

(2 is always less than 4, so (3 is never be able to exceed 5, so
While...do get an infinite loop) Repeat...until goes forever).

Or you might just:

While true do OR Repeat
begin
(bla bla bla ...)
(bla bla bla ...)
end; OR Until false;

(They yield the same effect as previous examples : infinite loops).

You may also nest the loop, i.e. a 'for' inside another 'for', a 'While' in another 'While', etc. And even, you may nest one form of loop inside another form, like a 'for' inside 'Repeat...Until'. Example :

Repeat
:
For ... do
begin
:
end;
:
Until ...;

It is perfectly legal.

How about if I want to bail out in a middle of loops ? Easy, use Break.
Example :
begin
   for i:=1 to 10 do
    begin
      writeln(i);
      if i=5 then break;
    end;
   writeln('Finished !');
end.
It yields :
1
2
3
4
5
Finished

Got it ? Break means go out from current loop. It can also be applied on while...do and repeat...until. How about nested loop ? Break only applies on its begin...end block. Check out the program below :
begin
for i:=1 to 4 do
 begin
    for j:=1 to 5 do
     begin
       writeln(i,' ',j);
       if j=3 then break;
     end;
    writeln('Next i loop');
 end;
writeln('Finished !');
end.

It yields :
1 1
1 2
1 3
Next i loop
2 1
2 2
2 3
Next i loop
3 1
3 2
3 3
Next i loop
4 1
4 2
4 3
Next i loop
Finished !

Another example :
begin
   for i:=1 to 5 do
     begin
       for j:=1 to 3 do
         begin
          writeln(i,' ',j);
         end;
       if i=2 then break;
     end;
   writeln('Finished !');
end.

It yields :
1 1
1 2
1 3
2 1
2 2
2 3
Finished !

Break only does its function in its current scope (begin...end block) How about if I want to skip instead of quitting current loop ? Well, use Continue instead of Break. Replace all Break in previous examples with Continue and see what happens.

Random and randomize
All of them are used to generate random numbers. Random numbers are always used to simulate the reality, where certainty is hardly guaranteed. We are here not to discuss how to make it, but how to use these two commands.

Randomize is used to start the random generator, so that it is only used at the first initialization, placed after the begin in the main block. It is enough to call it once, eventhough it may be called several times.

Random is used to get the random number. Its parameter is the highest possible number that can be generated. Suppose : num:=random(50); It means that num will contain any integer number between 0 to 49.

Look at next example :

var
   i : byte;
begin
   randomize;
   for i:=1 to 100 do
   write(random(30),' ');
end.

Let's remove the "randomize". Run it for several times and note that when it runs, if you don't use "randomize", the computer will result the same number. So, always use the "randomize" so that the computer generate quite
a good random numbers.

Halt
Just stop and return to system. Usage : Halt; You may place it anywhere you want. If computer encounters the "halt", it will stop the program execution and back to the operating system (DOS/Windows).

ASCII characters
There are 128 basic ASCII characters and 128 extended ASCII characters.
Writing ASCII characters is as simple as using writeln; Example :

writeln(#30); { Writing ASCII code 30 }

Try changing 30 with other numbers between 0 to 255.

Next Month: Functions And Procedures

Any questions send them to pascaltut@teentwo@8m.com

[ Pascal Tutor ] Pascal Graphics ] Pascal Math ] Pascal Misc ]

Link of the week 
http://www.cpp-
programming.
com/
Newsgroups
comp.lang.c
comp.lang.c++
comp.programming

This page is best viewed in 800x600x256. This page was last edited Tuesday, June 27, 2000

1