0% found this document useful (0 votes)
577 views20 pages

Ascal Anguage Utorial

Uploaded by

baconawa
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
577 views20 pages

Ascal Anguage Utorial

Uploaded by

baconawa
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

PASCAL 

LANGUAGE TUTORIAL
This is the trial version of the Pascal Language Tutorial.

Example programs and answers to exercises are not included in the trial version that is viewable
online. If you are interested in obtaining these additional files, please register to download the
Pascal Language Trial ZIP file, Pastrial.zip, through our website
http://www.coronadoenterprises.com/download/

This tutorial teaches the entire Pascal programming language. It is composed of 16 chapters
which should be studied in order since topics are introduced in a logical order and build upon
topics introduced in previous chapters. This tutorial contains a strong emphasis on object
oriented programming and what it will do to improve the quality of your code. It is to the
students benefit to download the source code for the example programs, then compile and
execute each program as it is studied. The diligent student will modify the example program in
some way, then recompile and execute it to see if he understands the material studied for that
program. This will provide the student with valuable experience using his compiler.

The recommended method of study is to print the text for one or two chapters, locate the
example programs in the /src directory, and study the material by loading the example programs
in the compiler's editor for viewing.

Version 2.61 - September 29, 1996 - (Files restructured on May 2, 2001)

Introduction - What is Pascal and why study it?


Chapter 1 - What is a computer program?
Chapter 2 - Getting Started in Pascal
Chapter 3 - The Simple Pascal Data Type
Chapter 4 - Pascal Loops and Control Structures
Chapter 5 - Pascal Procedures and Functions
Chapter 6 - Arrays, Types, Constants, and Labels
Chapter 7 - Strings and String Procedures
Chapter 8 - Scalars, Subranges, and Sets
Chapter 9 - Records
Chapter 10 - Standard Input/Output
Chapter 11 - File Input/Output
Chapter 12 - Pointers and Dynamic Allocation
Chapter 13 - Units in Turbo Pascal
Chapter 14 - Encapsulation and Inheritance
Chapter 15 - Virtual Methods
Chapter 16 - Complete Sample Programs

Back to Pascal Main Page


 

What do I get in the trial version?

HTML Documentation - All 17 files listed above (plus the diagrams) are included for use
locally. There are no executable files in this group of files.

Source Code - Example programs and answers to exercises are not included in the trial version
that is viewable online. If you are interested in obtaining these additional files, please register to
download the Pascal Language Trial ZIP file, Pastrial.zip, through our website,
http://www.coronadoenterprises.com/download/

What do I get in the full version?

HTML Documentation - All 17 files listed above (plus the diagrams) are included for use
locally. There are no executable files in this group of files.

Source Code - All example programs. There are 97 source files which are all explained in the 16
chapters of text. There are no executable files in this group of files.

Answers to Exercises- The authors answers to all of the programming exercises. There are 23
source files. There are no executable files in this group of files.

Copyright © 1988-2004 Coronado Enterprises, a division of WebStrata IS - Last update, May 2, 2001
Gordon Dodrill - author - Please post any comments, suggestions or code snippets to our Code Board.
Pascal Tutorial - Intro

INTRODUCTION
IF YOU KNOW NOTHING ABOUT PASCAL

Assuming that you know nothing at all about Pascal, and in fact, that you may know nothing
about programming in general, we will begin to study Pascal. If you are already somewhat
familiar with programming and especially Pascal, you will probably want to skip very quickly
through the first few chapters. You should at least skim these chapters, and you should read the
remainder of this introduction.

A few comments are in order to get us started in the right direction. The sample programs
included with this tutorial are designed to teach you the basics of Pascal and they do not include
any clever or tricky code. Nearly all of the programs are really quite dumb as far as being useful
programs, but all will teach one or more principles of Pascal. I have seen one tutorial that
included a 12 page program as the first example. In fact there were only 2 example programs in
the entire tutorial, and it was impossible to glean the essentials of programming from that
system. For this reason, I will completely bypass any long programs until the very end of this
tutorial. In order to illustrate fundamental concepts used in Pascal programming, all programs
will be very short and concise until we reach the last chapter.

LARGER PASCAL PROGRAMS

Chapter 16 has some rather large programs to illustrate to you how to write a large program. It
would be a disservice to you to show you all of the constructs of Pascal and not show you how to
put them together in a meaningful way to build a large program. After completing all of the
fundamentals of Pascal, it will then be very easy for you to use the tools learned to build as large
a program as you desire or require for your next programming project.

Another problem I have noticed in example programs is the use of one word for all definitions.
For example, a sort program is stored in a file called SORT, the program is named Sort, and
various parts of the program are referred to as Sort1, Sort2, etc. This can be confusing since you
have no idea if the program name must be the same as the filename, or if any of the other names
were chosen to be the same because of some obscure rule not clearly documented. For this
reason, the example programs use completely arbitrary names whenever the choice of a name
adds nothing to the readability or clarity of a program. As an illustration of this, the first program
is named Puppy_Dog. This adds nothing to the understanding of the program but does illustrate
that the program name means nothing to the Pascal compiler concerning what the program does.

Due to the fundamental design of the Pascal language, certain words are "reserved" and can only
be used for their defined purposes. These are listed in your TURBO Pascal reference manual. All
of the sample programs in this tutorial are written with the reserved words in all lower-case
letters, and the user variables in lower case with the first letter capitalized since this is becoming
an accepted industry standard. Don't worry about what reserved words are yet, they will be
completely defined later.

In this tutorial, all reserved words, type names, variable names, and procedure and function
names will be listed in boldface type within the text as an aid to the student.

WHAT IS A COMPILER?

There are two methods used to run any computer program that is written in a readable form of
English. The first method is to use an interpreter. An interpreter is a program that looks at each
line of the "English" program, decides what the "English" on that line means, and does what it
says to do. If one of the lines is executed repeatedly, it must be scanned and analyzed each time,
greatly slowing down the solution of the problem at hand. A compiler, on the other hand, is a
program that looks at each "English" statement one time and converts it into a code that the
computer understands directly. When the compiled program is actually run, the computer does
not have to figure out what each statement means, it is already in a form that the computer can
run directly, resulting in much faster execution of the program.

This tutorial is written especially for Borland International's TURBO Pascal compilers version
5.0 through 7.0. These are very high quality compilers that can do nearly anything you will ask
them to do since they are so flexible. The original intent of this tutorial was to write it in such a
way that it would be completely generic and usable with any good Pascal compiler. The
programmers at Borland included a great many nonstandard aids for the Pascal language and
resulted in a very good product that has dominated the market for microcomputers. To
completely omit all of the extensions would do those of you with the Borland compiler a real
disservice, and to include the extensions would not allow other compilers to be used effectively
with this tutorial.

The decision was made to use the Borland extensions which may make the tutorial difficult to
use with other compilers. If you have a need to use Pascal with some other compiler, TURBO
Pascal is so inexpensive that it would be a wise decision to purchase a copy solely for the
purpose of learning the Pascal programming language, then moving to the other compiler on a
minicomputer or a mainframe using the accumulated knowledge to very quickly learn the
extensions provided by that particular compiler. At any rate, this tutorial will not teach you
everything you will ever need to know about Pascal. It will, however, teach you the
fundamentals and the advanced features of Pascal, but of even more importance is the knowledge
of Pascal terminology needed to progress on your own into more advanced topics of Pascal and
programming in general. You will find that experience will be your best teacher.

WHICH VERSION OF TURBO PASCAL?

Some of the example programs will not work with some of the earlier versions of TURBO
Pascal. This is primarily due to the fact that object oriented programming capabilities were added
to version 5.5, and improved on in later versions. Most of the example programs will work with
any version however. It should be pointed out that each successive version of TURBO Pascal has
been an improvement over the previous version since additional capabilities have been added,
and each new one compiles a little faster and results in smaller but faster executable code than
the previous version. Any of the versions of TURBO Pascal can be used to learn to program in
Pascal, so whichever version you have on hand will be adequate. Later, when you become more
versed in programming techniques, you may wish to upgrade to the absolute latest version.

EARLY VERSIONS OF TURBO PASCAL

Most of the files will compile properly with TURBO Pascal versions 2.0 through 4.0. No
warning will be given about which files will not compile with these versions since they have
been superseded for so long. If you are still using one of the earlier versions, it would be good
for you to purchase a newer version because of the flexibility.

WHAT ABOUT TURBO PASCAL VERSION 5.5 & NEWER?

Chapters 14 and 15 of this tutorial are written especially for TURBO Pascal version 5.5 and
newer to discuss the use of object oriented programming and how to use the Borland extensions.
Since the topic of object oriented programming is a very large and diverse field of study and only
a limited space is available to discuss it in this tutorial, these chapters will give you only a brief
overview of what it is and how to use it. You will find 13 complete example programs to get you
started in this new and very meaningful endeavor and this introduction should whet your appetite
to continue your study in more depth.

If you are using an early version of TURBO Pascal without the object oriented extensions, it
would pay you to upgrade so you can learn how to use this new programming method. Object
oriented programming has the potential to greatly improve the quality of your code and to reduce
the debugging time required.

PREPARATION FOR USE OF THIS TUTORIAL.

Copy the example files into your TURBO Pascal working directory and you are ready to begin,
provided of course that you have already learned how to start the TURBO system and how to
edit a Pascal file.

If you are not using TURBO Pascal, you will still be able to compile and execute many of these
Pascal files, since most of the examples use standard Pascal syntax. There will be some
statements used which are unique to TURBO Pascal and will not work with your compiler. This
will be especially true when you come to the chapter on standard input and output since this is
where most compilers differ. Unfortunately, this is one of the most important aspects of any
programming language, since it is required to get data into and out of the computer to do
anything useful. You will also find that chapter 13, covering the topic of units, is unique to
TURBO Pascal and will not work with any Pascal compilers other than TURBO Pascal.

WHAT ABOUT THE PROGRAMMING EXERCISES?

It is highly suggested that you do the programming exercises after you complete the study for
each chapter. They are carefully selected to test your understanding of the material covered in
that chapter. If you do not write, enter, debug, and run these programs, you will only be
proficient at reading Pascal. If you do the exercises completely, you will have a good start at
being a Pascal program writer.

It should also be mentioned that this tutorial will not teach you everything you will ever need to
know about Pascal. You will continue to learn new techniques as long as you continue to write
programs. Experience is the best teacher here just as it is in any endeavor. This tutorial will teach
you enough about Pascal that you should feel very comfortable as you search through the
reference manual for some topic. You will also be able to read and understand any Pascal
program you find in textbooks or magazines. Although the primary goal of this tutorial is to
teach you the syntax and use of Pascal, the most important byproduct is the knowledge of Pascal
terminology you will gain. This terminology will enable you to learn even more about Pascal and
programming in general.

THE ANSWERS TO PROGRAMMING EXERCISES

The directory /ans contains an answer to each of the programming exercises given at the end of
the chapters. You should attempt to do original work on each of the exercises before referring to
these answers, in order to gain your own programming experience. These answers are given for
your information in case you are completely stuck on how to solve a particular problem. These
answers are not meant to be the only answer, since there are many ways to program anything, but
they are meant to illustrate one way to solve the suggested programming problem.

The answers are all in compilable files named in the format CHnn_m.PAS where nn is the
chapter number, and m is the exercise number. If there is more than one answer required, an A,
B, or C is included following the exercise number.

Advance to Chapter 1

Return to the Table of Contents

Copyright © 1988-2004 Coronado Enterprises, a division of WebStrata IS - Last update, May 2, 2001
Gordon Dodrill - author - Please post any comments, suggestions or code snippets to our Code Board.
Pascal Tutorial - Chapter 1

WHAT IS A COMPUTER PROGRAM?


THIS CHAPTER IS FOR NEW PROGRAMMERS

If you are a complete novice to computers you will find the information in this chapter useful. If
however, you have had some experience with programming, you can completely ignore this
chapter. It will deal with a few fundamentals of computers in general and will introduce nothing
that is specific to Pascal.

WHAT IS A COMPUTER PROGRAM?

A computer is nothing but a very dumb machine that has the ability to perform mathematical
operations very rapidly and very accurately, but it can do nothing without the aid of a program
written by a human being. Moreover, if the human being writes a program that turns good data
into garbage, the computer will very obediently, and very rapidly, turn the good data into
garbage. It is possible to write a computer program with one small error in it that will do that
very thing, and in some cases appear to be generating good data. It is up to the human
programmer to design a program to achieve the desired results.

A computer program is simply a "recipe" which the computer will use on the input data to derive
the desired output data. It is similar to the recipe for baking a cake. The input data is comparable
to the ingredients, including the heat supplied by the oven. The program is comparable to the
recipe instructions to mix, stir, wait, heat, cool, and all other possible operations on the
ingredients. The output of the computer program can be compared to the final cake sitting on the
counter ready to be cut and served. A computer program is therefore composed of two parts, the
data upon which the program operates, and the program that operates on the data. The data and
program are inseparable as implied by the last sentence.

WHAT ARE CONSTANTS?

Nearly any computer program requires some numbers that never change throughout the program.
They can be defined once and used as often as needed during the operation of the program. To
return to the recipe analogy, once you have defined how big a tablespoon is, you can use the
same tablespoon without regard to what you are measuring with it. When writing a computer
program, you can define the value of PI = 3.141592, and continue to use it wherever it makes
sense knowing that it is available, and correct.

WHAT ARE VARIABLES?

In addition to constants, nearly every computer program uses some numbers that change in value
throughout the program. They can be defined as variables, then changed to any values that make
sense to the proper operation of the program. An example would be the number of eggs in the
above recipe. If a single layer of cake required 2 eggs, then a triple layer cake would require 6
eggs. The number of eggs would therefore be a variable.

HOW DO WE DEFINE CONSTANTS OR VARIABLES?

All constants and variables have a name and a value. In the last example, the name of the
variable was "eggs", and the value was either 2 or 6 depending on when we looked at the stored
data. In a computer program the constants and variables are given names in much the same
manner, after which they can store any value within the defined range. Any computer
programming language has a means by which constants or variables can be first named, then
assigned a value. The means for doing this in Pascal will be given throughout the remainder of
this tutorial.

WHAT IS SO GOOD ABOUT PASCAL?

Some computer languages allow the programmer to define constants and variables in a very
haphazard manner and then combine data in an even more haphazard manner. For example, if
you added the number of eggs, in the above recipe, to the number of cups of flour, you would
arrive at a valid mathematical addition, but a totally meaningless number. Some programming
languages would allow you to do just such an addition and obediently print out the meaningless
answer. Since Pascal requires you to set up your constants and variables in a very precise
manner, the possibility of such a meaningless answer is minimized. A well written Pascal
program has many cross checks to minimize the possibility of a completely scrambled and
meaningless output.

Notice however, in the last statement, that a "well written" Pascal program was under discussion.
It is still up to the programmer to define the data structure in such a way that the program can
help prevent garbage generation. In the end, the program will be no better than the analysis that
went into the program design.

If you are a novice programmer, do not be intimidated by any of the above statements. Pascal is a
well designed, useful tool that has been used successfully by many computer novices and
professionals. With these few warnings, you are ready to begin.

Advance to Chapter 2

Return to the Table of Contents

Copyright © 1988-2004 Coronado Enterprises, a division of WebStrata IS - Last update, May 2, 2001
Gordon Dodrill - author - Please post any comments, suggestions or code snippets to our Code Board.
Pascal Tutorial - Chapter 2

GETTING STARTED IN PASCAL


YOUR FIRST PASCAL PROGRAM

Example program ------> TRIVIAL.PAS

Lets get right into a program that really does nothing, but is an example of the most trivial Pascal
program. Load Turbo Pascal, then load TRIVIAL.PAS into the integrated environment as a work
file. This assumes you have been successful in learning how to use the TURBO Pascal system.

You should now have the most trivial Pascal program possible on your display, and we can take
a look at each part to define what it does.

The first line is required in the standard Pascal definition and contains the program name which
can be any name you like, as long as it follows the rules for an identifier given in the next
section. It can have no blanks, otherwise it would be considered as two words and it would
confuse the compiler. The first word program is the first of the reserved words mentioned
earlier and it is the indicator to the Pascal compiler that this is the name of the program. The
second word, Puppy_Dog, is the program name itself. Notice that the line ends with a
semicolon. Pascal uses the semicolon as a statement separator and although all statements do not
actually end in a semicolon, most do, and the proper use of the semicolon will clear up later in
your mind.

TURBO Pascal does not require the program statement, but to remain compatible with standard
Pascal, it will simply ignore the entire statement. It is recommended that you include a program
name both to aid your thinking in standard Pascal, and to add a little more indication of the
purpose of each program.

WHAT IS AN IDENTIFIER?

All identifiers, including the program name, procedure and function names, type definitions, and
constant and variable names, will start with an alphabetical character and be composed of any
combination of alphabetic and numeric characters with no embedded blanks. Upper or lower
case alphabetic characters are not significant and may be mixed at will. (If you find this
definition confusing at this point, don't worry about it, it will be clear later but it must be defined
early). The standard definition of Pascal requires that any implementation (i.e. any compiler
written by some company) must use at least 8 characters of the identifier as significant and may
ignore the remaining characters if more than 8 are used. Most implementations use far more than
8. All versions of TURBO Pascal use 63 characters in an identifier as being significant.

Standard Pascal does not allow the use of underlines in an identifier but most implementations of
Pascal allow its use after the first character. All versions of TURBO Pascal compilers permit the
use of the underline in an identifier, so it will be freely used throughout this tutorial. The
underline is used in the program name Puppy_Dog which should be on your display at this time.

Returning to the example program, line 2 is a blank line. Blank lines are ignored by all Pascal
compilers. More will be said about the blank line at the end of this chapter.

NOW FOR THE PROGRAM

Lines 3 and 4 comprise the actual Pascal program, which in this case does absolutely nothing.
This is an illustration of the minimum Pascal program. The two words begin and end are the
next two reserved words we will consider. Any logical grouping of Pascal code can be isolated
by bracketing it with the two reserved words begin and end. You will use this construct
repeatedly as you write Pascal code, so it is well to learn it thoroughly. Code to be executed by
conditional jumps will be bracketed by begin and end, as will code within a loop, and code
contained within a subroutine (although they are called procedures in Pascal), and in many other
ways. In the present program, the begin and end are used to bracket the main program and every
Pascal program will have the main program bracketed in this manner. Because there is nothing to
do in this program, there are no statements between the begin and end reserved words.

Finally, although it could be very easily overlooked, there is one more very important part of the
program, the period following the reserved word end. The period is the signal to the compiler
that it has reached the end of the executable statements and is therefore finished compiling.
Every Pascal program will have one, and only one period in it, and that one period will be at the
end of the program. I must qualify that statement in this regard, a period can be used in
comments, and in text to be output. In fact there are some data formats that require using a period
as part of their structure. Think of a Pascal program as one long sentence with one period at the
end. Ignore lines 9 through 13 for a few minutes and we will describe them fully later.

That should pretty well describe our first program. Now it is time for you to compile and run it.
Since this program doesn't do anything, it is not very interesting, so let's look at one that does
something.

A PROGRAM THAT DOES SOMETHING

Example Program ------> WRITESM.PAS

Load the Pascal program WRITESM.PAS and view it on your monitor. The filename is sort of
cryptic for "Write Some" and it will display a little output on the monitor. The program name is
Kitty_Cat which says nothing about the program itself but can be any identifier we choose. We
still have the begin and end to define the main program area followed by the period. However,
now we have two additional statements between the begin and end. Writeln is a special word
and it is probably not surprising that it means to write a line of data somewhere. Without a
modifier, which will be fully explained in due time, it will write to the default device which, in
the case of our IBM compatible, is the video display. The data within the parentheses is the data
to be output to the display and although there are many kinds of data we may wish to display, we
will restrict ourselves to the simplest for the time being. Any information between apostrophes
will simply be output as text information.

The special word Writeln is not a reserved word but is defined by the system to do a very
special job for you, namely to output a line of data to the monitor. It is, in fact, a procedure
supplied for you by the writers of TURBO Pascal as a programming aid for you. You can, if you
so desire, use this name for some other purpose in your program, but doing so will not allow you
to use the standard output procedure. It will then be up to you to somehow get your data out of
the program.

Note carefully that some words are reserved and cannot be redefined and used for some other
purpose, and some are special since they can be redefined. You will probably not want to
redefine any of the special words for a long time. Until you gain considerable programming
experience, simply use them as tools.

Notice the semicolon at the end of line 4. This is the statement separator referred to earlier and
tells the Pascal compiler that this line is complete as it stands, nothing more is coming that could
be considered part of this statement. The next statement, in line 5, is another statement that will
be executed sequentially following the statement in line 4. This program will output the two lines
of text and stop.

Now it is time to go try it. Compile and run this program. You should see the two lines of text
output to the video display every time you run this program. When you grow bored of running
WRITESM.PAS let's go on to another example.

ANOTHER PROGRAM WITH MORE OUTPUT

Example program ------> WRITEMR.PAS

Examine the example program named WRITEMR.PAS. This new program has three lines of
output but the first two are different because another special word is introduced to us, namely
Write. Write is a procedure which causes the text to be output in exactly the same manner as
Writeln, but Write does not cause a carriage return to be output. Writeln causes its output to
take place, then returns the "carriage" to the first character of the next line. The end result is that
all three of the lines of text will be output on the same line of the monitor when the program is
run. Notice that there is a blank at the end of each of the first two lines so that the formatting will
look nice. Compile and execute the new program.

Now might be a good time for you to return to editing WRITEMR.PAS and add a few more
output commands to see if they do what you think they should do. When you tire of that, we will
go on to the next file and learn about comments within a Pascal program.

ADDING COMMENTS IN THE PROGRAM

Example program ------> PASCOMS.PAS


The file named PASCOMS.PAS is similar to the others except that comments have been added
to illustrate their use. Pascal defines comments as anything between (* and *) or anything
between { and }. Originally only the wiggly brackets were defined, but since many keyboards
didn't have them available, the parenthesis star combination was defined as an extension and is
universal by now, so you can use either. Most of the comments are self explanatory except for
the one within the code. Since comments can go from line to line, lines 11 and 12 that would
normally print "send money", are not Pascal code but are commented out by the comment
delimiters in lines 10 and 13. Try compiling and running this program, then edit the comment
delimiters out so that "send money" is printed also.

A fine point should be mentioned here. Even though some compilers allow comments to start
with (* and end with }, or to start with { and end with *), it is very poor programming practice
and should be discouraged. The ANSI Pascal standard allows such usage but TURBO Pascal
does not permit this funny use of comment delimiters.

TURBO Pascal does not allow you to nest comments using the same delimiters but it does allow
you to nest one type within the other. This could be used as a debugging aid. If you generally use
the (* and *) for comments, you could use the { and } in TURBO Pascal to comment out an
entire section of code during debugging even if it had a few comments in it. This is a trick you
should remember when you reach the point of writing programs of significant size.

When you have successfully modified and run the program with comments, we will go on to
explain good formatting practice and how Pascal actually searches through your source file
(Pascal program) for its executable statements.

It should be mentioned that the program named PASCOMS.PAS does not indicate good
commenting style. The program is meant to illustrate where and how comments can be used and
looks very choppy and unorganized. Further examples will illustrate good use of comments to
you as you progress through this tutorial.

THE RESULT OF EXECUTION SECTION

You should now be able to discern the purpose for lines 20 through 26 of this program. Each of
the example programs in this tutorial lists the result of execution in a comments section at the
end of the program. This makes it possible to study this tutorial anywhere if you print out a hard
copy of the example programs. With this text, and a hard copy of the example programs
containing the result of execution, you do not need access to a computer to study. Of course you
would need access to a computer to write, compile, and execute the programming exercises,
which you are heartily encouraged to do.

GOOD FORMATTING PRACTICE

Example program ------> GOODFORM.PAS

Examine GOODFORM.PAS to see an example of good formatting style. It is important to note


that Pascal doesn't give a hoot where you put carriage returns or how many blanks you put in
when a blank is called for as a delimiter. Pascal only uses the combination of reserved words and
end-of-statement semicolons to determine the logical structure of the program. Since we have
really only covered two executable statements, I have used them to build a nice looking program
that can be easily understood at a glance. Compile and run this program to see that it really does
what you think it should do.

VERY POOR FORMATTING PRACTICE

Example program ------> UGLYFORM.PAS

Examine UGLYFORM.PAS now to see an example of terrible formatting style. It is not really
apparent at a glance but the program you are looking at is exactly the same program as the last
one. Pascal doesn't care which one you ask it to run because to Pascal, they are identical. To you
they are considerably different, and the second one would be a mess to try to modify or maintain
sometime in the future.

UGLYFORM.PAS should be a good indication to you that Pascal doesn't care about
programming style or form. Pascal only cares about the structure, including reserved words and
delimiters such as blanks and semicolons. Carriage returns are completely ignored as are extra
blanks. You can put extra blanks nearly anywhere except within reserved words or variable
names. You should pay some attention to programming style but don't get too worried about it
yet. It would be good for you to simply use the style illustrated throughout this tutorial until you
gain experience with Pascal. As time goes by you will develop a style of statement indentation,
adding blank lines for clarity, and a method of adding clear comments to Pascal source code.
Programs are available to read your source code, and put it in a "pretty" format, but that is not
important now.

Not only is the form of the program important, the names used for variables can be very helpful
or hindering as we will see in the next chapter. Feel free to move things around and modify the
format of any of the programs we have covered so far and when you are ready, we will start on
variables in the next chapter. Be sure you compile and execute UGLYFORM.PAS.

PROGRAMMING EXERCISES

1. Write a program that displays your name on the video monitor.


2. Modify your program to display your name and address on one line, then modify it by
changing the Write's to Writeln's so that the name and address are on different lines.

Advance to Chapter 3

Return to the Table of Contents

Copyright © 1988-2004 Coronado Enterprises, a division of WebStrata IS - Last update, May 2, 2001
Gordon Dodrill - author - Please post any comments, suggestions or code snippets to our Code Board.
Pascal Tutorial - Chapter 3

THE SIMPLE PASCAL DATA TYPE


WHAT IS A DATA TYPE?

A type in Pascal, and in several other popular programming languages, defines a variable in such
a way that it defines a range of values which the variable is capable of storing, and it also defines
a set of operations that are permissible to be performed on variables of that type. TURBO Pascal
has eight basic data types which are predefined and can be used anywhere in a program provided
you use them properly. This chapter is devoted to illustrating the use of these eight data types by
defining the allowable range of values that can be assigned to them, and by illustrating the
operations that can be done to variables of these types. The eight types and a very brief
description follows;

integer Whole numbers from -32768 to 32767


byte The integers from 0 to 255
real Floating point numbers from 1E-38 to 1E+38
boolean Can only have the value TRUE or FALSE
char Any character in the ASCII character set
shortint The integers from -128 to 127
word The integers from 0 to 65535
longint The integers from -2147483648 to 2147483647

Please note that four of these types of data (char, shortint, word, and longint) are not a part of the
standard Pascal definition but are included as extensions to the TURBO Pascal compiler.

In addition to the above data types TURBO Pascal version 5.0 and later have the following data
types available;

single Real type with 7 significant digits


double Real type with 15 significant digits
extended Real type with 19 significant digits
comp The integers from about -10E18 to 10E18

TURBO Pascal version 5.0 and newer have these four types available which use the 80X87 math
coprocessor. Because TURBO Pascal has a software emulator for the floating point operations,
an 80X87 math coprocessor is not absolutely required to use these new types with these versions.
Of course, your resulting program will run much faster if you have the coprocessor available for
use by the program. Note that the math coprocessor is built into every 80486 and Pentium
processor.

A complete definition of the available types for each compiler can be found in your TURBO
Pascal reference manual. It would be good to read these pages now for a good definition prior to
learning how to define and use them in a program. Note that all of these will be used in example
programs in this chapter.
OUR FIRST VARIABLES

Example program ------> INTVAR.PAS

The integers are by far the easiest to understand so we will start with a simple program that uses
some integers in a very simple way. Load INTVAR.PAS into your Pascal system and let's take a
look at it.

Immediately following the program statement is another reserved word, var. This reserved word
is used to define a variable before it can be used anywhere in the program. There is an unbroken
rule of Pascal that states "Nothing can be used until it is defined." The compiler will complain by
indicating a compilation error if you try to use a variable without properly defining it. It seems a
bit bothersome to have to define every variable prior to its use, but this rule will catch many
spelling errors of variables before they cause trouble. Some other languages will simply define a
new variable with the new name and go merrily on its way producing some well formatted
garbage for you.

Notice that there is only one use of the reserved word var, but it is used to define three different
variables, Count, X, and Y. Once the word var is recognized, the compiler will continue to
recognize variable definitions line after line until it finds another reserved word. It would be
permissible to put a var on the second line also but it is not necessary. It would also be
permissible to put all three variables on one line but your particular programming style will
dictate where you put the three variables. Following the colon on each line is the word integer
which is a standard identifier, and is therefore different from a reserved word. A standard
identifier is predefined like a reserved word, but you can redefine it, thereby losing its original
purpose and meaning. For now and for a long time, don't do that.

OUR FIRST ARITHMETIC

Now that we have three variables defined as integer type variables, we are free to use them in a
program in any way we desire as long as we use them properly. If we tried to assign a real value
to X, the compiler will generate an error, and prevent a garbage output. Observe the start of the
main body of the program. There are three statements assigning values to X, Y, and Count. A
fine point of mathematics would state that Count is only equal to the value of X+Y until one of
them is modified, therefore the equal sign used in so many other languages is not used here. The
sign := is used, and can be read as "is replaced by the value of," when reading a listing. Another
quicker way is to use the word "gets". Thus X := X + 1 would be read, "X gets the value of X
plus 1". We will see later that the simple equal sign is reserved for another use in Pascal.

The first three statements give X the value of 12, Y the value of 13, and Count the value of 12 +
13 or 25. In order to get those values out of the computer, we need another extension to the
Writeln statement. The first part of the data within the parentheses should be very familiar to
you now, but the second part is new.

Multiple outputs can be handled within one Writeln if the fields are separated by a comma. To
output a variable, simply write the variable's name in the output field. The number following the
variable in each case is the number of output columns to be used by the output data. This number
is optional and can be omitted allowing the system to use as many columns as it needs. For
purposes of illustration, they have all been assigned different numbers of columns. At this point,
you can compile and run INTVAR.PAS and examine its output.

Example program ------> INTVAR2.PAS

To illustrate the various ways to output data, load INTVAR2.PAS and observe that even though
the output is identical, it is output in a completely different manner. The Writeln statements are
broken into pieces and the individual pieces are output with Write and Writeln statements.
Observe especially that a Writeln all by itself simply moves the cursor to the beginning of a new
line on the video monitor.

Compile and run this program and observe its output after you are certain that the two programs
are actually identical.

NOW LET'S USE LOTS OF VARIABLES

Example program ------> ALLVAR.PAS

Load ALLVAR.PAS to observe a short program using five of the basic data types. The variables
are assigned values and the values are printed. A complete and detailed description of the options
available in the Write statement is given in your TURBO Pascal reference manual. Check the
index to find this information for the version you are using. It would be to your advantage to read
this section now since very little explanation will be given about Write statements from this
point on. We will discuss the method by which we can write to disk files or other output devices
in a later chapter of this tutorial.

Back to the basic types. Pascal does lots of cross checking for obvious errors. It is illegal to
assign the value of any variable with a value that is of the wrong type or outside the allowable
range of that variable. There are routines to convert from one system to another when that is
necessary. Suppose, for example, that you wished to use the value of an integer in a calculation
of real numbers. That is possible by first converting the integer into a real number of the same
value and using the new real type variable in the desired calculations. The new real type
variable must of course be defined in a var statement as a real type variable before it can be
used. Details of how to do several conversions of this kind will be given in the example program
named CONVERT.PAS later in this chapter.

Example program ------> REALMATH.PAS

Since we have some variables defined, it would be nice to use the properties of computers for
which they are famous, namely some arithmetic. Two programs are available for your
observation to illustrate the various kinds of math available, REALMATH.PAS using real
variables, and INTMATH.PAS using integer variables. You can edit, compile, and run these on
your own with no further comment from me except the comments embedded into the source
files. You should output some of the results using the method of outputting illustrated in the
previous example program. Read the definition of how to do this in your TURBO Pascal User's
Guide.

Example program ------> INTMATH.PAS

The example program named INTMATH.PAS illustrates some of the math capabilities of Pascal
when using integer type variables. A byte type variable is used just like an integer variable but
with a much smaller allowable range. Only one byte of computer memory is used for each
variable defined as a byte type variable, but 2 are used for each integer type variable.

BOOLEAN VARIABLES

Example program ------> BOOLMATH.PAS

Let's take a look at a boolean type variable, which is only allowed to take on two different
values, TRUE or FALSE. This variable is used for loop controls, end of file indicators or any
other TRUE or FALSE conditions in the program. Variables can be compared to determine a
boolean value. A complete list of the relational operators available with Pascal is given in the
following list.

= equal to
<> not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

These operators can be used to compare any of the simple types of data including integer, char,
byte, and real type variables or constants, and they can be used to compare boolean variables.
An illustration is the best way to learn about the boolean variable so load BOOLMATH.PAS
and observe it.

In BOOLMATH.PAS we define a few boolean variables and two integer type variables for use
in the program and begin by assigning values to the two integer variables. The expression Junk
= Who in line 14 is actually a boolean operation that is not true since the value of Junk is not
equal to the value of Who, The result is therefore FALSE and that value is assigned to the
boolean variable A. The boolean variable B is assigned the value of TRUE because the boolean
expression Junk = (Who - 1) is true. The boolean variables C and D are likewise assigned some
values in a manner that should not need any comment. After assigning a value to the variable
with the big name, the values are all printed out. Note that if either A or B is TRUE, the result is
TRUE in line 18.

WHERE DO WE USE THE BOOLEAN VARIABLES?

We will find many uses for the boolean type variable when we study the loops and conditional
statements soon, but until then we can only learn what they are. Often, in a conditional statement,
you will want to do something if both of two things are true, in which case you will use the
reserved word and with two boolean expressions. If both are true, the result will be true. Line 29
is an example of this. If the boolean variables B, C, and D, are all true, then the result will be
true and A will be assigned the value of TRUE. If any one of them is false, the result will be
false and A will be assigned the value of FALSE.

In Line 31, where the or operator is illustrated, if any of the three boolean variables is true, the
result will be true, and if all three are false, the result will be false. Another boolean operator is
the not which is illustrated in line 30 and inverts the sense of the boolean variable D. Examine
line 33 which says the result is true only if the variable Junk is one less than Who, or if Junk is
equal to Who. This should indicate the level of flexibility available with a boolean variable.

Compile and run this program, then add some additional printout to see if the boolean variables
change in the manner you think they should in the last few statements.

SHORT CIRCUIT OR COMPLETE EVALUATION?

Suppose you have several boolean expressions "and"ed together, and when evaluation starts, the
first expression results in a FALSE. Since the first expression is FALSE, it is impossible for the
following expressions to ever allow the final result to be TRUE because the first FALSE will
force the answer to be FALSE. It seems like a waste of execution time to continue evaluating
terms if the final result is already known, but that is exactly what standard Pascal will do because
of the language definition. This is known as complete evaluation of a boolean expression. If the
system is smart enough to realize that the final result is known, it could stop evaluation as soon
as the final result is known. This is known as short circuit evaluation of a boolean expression,
and could also be applied if a term of an "or"ed boolean expression resulted in a TRUE, since
the result would always be TRUE.

TURBO Pascal versions 5.0 and later, allows you to choose between complete evaluation or
short circuit evaluation. The default for these compilers is the short circuit form but it can be
changed through the Options menu when you are using the integrated environment, or through
use of a compiler directive.

LET'S LOOK AT THE CHAR TYPE VARIABLE

Example program ------> CHARDEMO.PAS

A char type variable is a very useful variable, but usually not when used alone. It is very
powerful when used in an array or some other user defined data structure which is beyond the
scope of this chapter. A very simple program, CHARDEMO.PAS is included to give you an idea
of how a char type variable can be used. Study, then compile and run CHARDEMO.PAS for a
very brief idea of what the char type variable is used for.

Example program ------> CONVERT.PAS


Examine the sample program CONVERT.PAS for several examples of converting data from one
simple variable to another. The comments make the program self explanatory except for the
strings which we will study in chapter 7 of this tutorial.

EXTENDED INTEGER TYPES

Example program ------> EXTINT.PAS

Display the program EXTINT.PAS for an example of using the extended integer types available
with the Pascal compiler. Four variables are defined and values assigned to each, then the results
are displayed. When you compile and run the program, you will see that the variable Big_int can
indeed handle a rather large number.

It must be pointed out that the calculation in lines 13 and 21 result in a different answer even
though they appear to be calculating the same thing. An explanation is in order. The quantity
named MaxInt used in lines 10 and 13 is a constant built into the system that represents the
largest value that an integer type variable can store. On the first page of this chapter we defined
that as 32767 and when running the program you will find that Index displays that value as it
should. The constant MaxInt has a type that is of a universal_integer type as do all of the
numeric constants in line 13. The result then is calculated to the number of significant digits
dictated by the left hand side of the assignment statement which is of type longint resulting in a
very large number.

When we get to line 21, however, the variable Index is of type integer so the calculations are
done as though the constants were of type integer also which causes some of the more
significant digits to be truncated. The truncated result is converted to type longint and assigned
to the variable Big_int and the truncated value is displayed by line 22.

After that discussion it should be apparent to you that it is important what types you use for your
variables. It must be emphasized that it would not be wise to use all large type variables because
they use more storage space and slow down calculations. Experience will dictate the proper data
types to use for each application.

EXTENDED REAL TYPES

Example Program ------> EXTREAL.PAS

Display the program EXTREAL.PAS for an example using the new "real" types available with
the newer versions of TURBO Pascal.

If you are using a version of TURBO Pascal which is 5.0 or newer, you can use the 80X87 math
coprocessor.

This program should be self explanatory so nothing will be said except that when you run it, you
can observe the relative accuracy of each of the variable types. Once again, you should keep in
mind that use of the larger "real" types costs you extra storage space and reduced run-time
speed, but gives you more accuracy.

PROGRAMMING EXERCISE

1. Write a program containing several variable definitions and do some math on them,
printing out the results.

Return to the Table of Contents

Copyright © 1988-2004 Coronado Enterprises, a division of WebStrata IS - Last update, May 2, 2001
Gordon Dodrill - author - Please post any comments, suggestions or code snippets to our Code Board.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy