Chapter 1
Introduction to DOS

Chapter 2
Introduction to Turbo Pascal

Chapter 3
Parts of a Pascal Program

Chapter 4
Control Structures and Looping

Chapter 5
Looping

Chapter 6
Procedures

Chapter 7
Parameters Passing

Chapter 8
Functions

Chapter 9
Arrays

Chapter 10
Searching and Sorting

Chapter 11
Records and File of Records

CHAPTER 3

( Parts of a Pascal Program )

PROGRAM HEADING :

example: program InventoryControl (input, output);

A Pascal program heading begins with the reserved word 'program' followed by a user defined identifier, that gives the name of the program. Input/output files used in the program can be identified within parentheses. Like all other valid Pascal statements there should be a semicolon at the end to separate this statement from the next one.

DECLARATION OF TYPES, CONSTANTS, AND VARIABLES :

example: const SalesTaxRateForTexas = 0.07;

type YearsOfReagenPresidency = 1980..1988;

var StudentGrade : Real;

In Pascal the type of all variables must be declared. Data types can be pre-defined types or user-defined types. Examples of a user defined type are shown above, 'YearsOfReagenPresidency'. We will have a great deal more to say about this in later chapters. When declaring a constant of predefined data type, it is not necessary to indicate what type it is. In the above example, the Pascal compiler will determine that 0.07 is a real number.

 

PROGRAM BODY (STATEMENT PART):

The program body is enclosed in a begin-end pair followed by a period. This portion contains a series of instructions called statements. All statements within these pairs should be separated by semicolons except for the statement immediately prior to the 'end'. You can use as many begin-end pairs as you wish. However, the last 'end' in a program must be followed by a period. Compound statements should be enclosed in a begin-end pair. The program body might include the following: ASSIGNMENT STATEMENTS, ARITHMETIC OPERATIONS, INPUT/OUTPUT STATEMENTS, PROCEDURES, FUNCTIONS, etc.

We can use all the standard functions and procedures that come bundled with Turbo Pascal and we can write our own. When we write our own functions and procedures, those must be written before beginning the main program.

OPERATORS:

:= THIS IS ASSIGNMENT OPERATOR. Eg. Age := 37

+ ADD

- SUBTRACT

* MULTIPLY

DIV INTEGER DIVISION. Eg. 9 MOD 4 = 2

MOD YIELDS REMAINDER OF A DIVISION. Eg. 9 DIV 4 = 1

OPERATOR PRECEDENCE: * / DIV MOD ARE COMPLETED BEFORE + -

When parentheses are used, calculations are done from

inside out.

Boolean operators will be discussed in the next chapter.

In addition to the operators above, Pascal provides a number of standard functions such as sqr, sin, exp, and succ which returns a single value. These functions can be used within the body of the program.

Now let us write a program using some of these program parts. This is a program where the computer reads your mind. See if you can figure out what the trick is.

The steps performed by this program are:

1. Find a small even random number to be used later.

2. Ask the user to think of a small number.

3. Ask the user to perform a series of simple mathematical

    operations on that number.

4. When finished, surprise him/her with the answer.

5. Give plenty of time between steps. To do this, prompt

Ready? and allow the user to type in something from the keyboard. This input is discarded; not used by the program. I called the variable that holds the value of this input 'nothing'.

Notice that I am not telling you how it arrived at the answer at step 4. If I told you that it will take all the fun out of this program. Keep running it, the trick will become obvious to you.

Before you can write a program you need to be in the Turbo Pascal Editor. If you don't know how to get into the editor please read Appendix 2A. Just to refresh your memory:

cd \tp <Enter>

turbo <Enter>

When you see the Turbo Pascal menu choose Edit.

Type the following program in.

PROGRAM 3-1

PROGRAM Magician (input, output);

VAR

Nothing : char;

PlayerName: string;

AddNumber : integer;

Answer : real;

BEGIN

{You don't need to know what this section is doing,

it is little advanced. Just type it in.}

randomize;

AddNumber := random(9)+1;

if AddNumber mod 2 > 0

then AddNumber:= AddNumber+1;

{The rest of the program should be easy enough.}

Program continued..

write('Welcome to the world of Magic! ');

write('What is your name? '); readln(PlayerName);

writeln;

writeln('--------------------------------------------------');

writeln(PlayerName,', think of a number between 1-10');

writeln ('Don''t tell me the number. You will need this

number later.');

write ('So don''t forget it. Are you ready? (answer YES to

all questions ');

readln(nothing);

write ('Now, double that number. Ready? '); readln(nothing);

write ('Add' ,AddNumber:3, ' to it. Ready? ');

readln(nothing);

write ('Now, find the half of the number. Ready? ');

readln(nothing);

write (PlayerName, ', subtract the very first number. Ready?

');

readln(nothing);

write ('Finally, add 3 to the answer. Ready? ');

readln(nothing);

answer := AddNumber/2+3;

writeln;

writeln ('****************************************');

writeln (' I know your answer, IT IS ',Answer:1:0);

writeln ('****************************************');

writeln;

writeln;

writeln ('If it did not work out, try again, and check your

math!');

writeln;

write('Ready? ');readln(nothing);

END.

Here is a sample run:

C:\TP>

Welcome to the world of Magic! What is your name? Ron

--------------------------------------------------

Ron, think of a number between 1-10

Don't tell me the number. You will need this number later;

so don't forget it. Are you ready? (answer YES to all questions)

YES

Now, double that number. Ready? YES

Add 8 to it. Ready? YES

Now, find the half of the number. Ready? YES

Ron, subtract the very first number. Ready? YES

Finally, add 3 to the answer. Ready? YES

****************************************

I know your answer, IT IS 7

****************************************

If it did not work out, try again, and check your math!

Ready?

After typing the program in press F10. Choose FILE and save

this program. It will ask for a file name, and you give it a name. Magician.pas would be a good name for this program. Run it and see how the program appears to read your mind.

EXPLANATION

Let us talk about this program. A Pascal program begins with a reserved word PROGRAM and then a program name of your choice. Input and output given in parentheses tells the Pascal compiler that we are going to be using the keyboard for input and monitor for output.

The VAR section has some new variable types. A Char variable is used to store a character. A String variable is composed of several characters. A string variable would be good to use when you want to store a person's name. A Real variable is used to store numbers with a decimal. An Integer variable is

used to store whole numbers. Remember, a variable is the name

of a memory location (or group of memory locations) where a

value would be stored. Be sure to read Appendix 3A to learn more about variables and types.

The next section is enclosed in the BEGIN END pair. After the BEGIN, a comment is enclosed in { }. Any thing enclosed in

these curly brackets are considered to be comments and skipped

by the Pascal compiler. You can type anything you want to as comments. Starting with the next program, you will begin to see a lot of comments inside the programs.

The first part of the program comes up with a small random

number. This number is used later in the program. The rest

of the program is mostly made up of read and write statements.

TEXT FILE HANDLING

Now that we learned about most important parts of a Pascal program, we will look at another very important aspect of Pascal programming - text file handling. In everyday life we write down information on paper so that we can refer to it later. This is because we know that we cannot rely on our memory always. Similarly if we placed something in a computer's main memory, we can only rely on that information as long as the computer is on. Once it is turned off all the information will be lost. Suppose we had just typed in names and addresses of two thousand students, we certainly would not want to lose this information. We could place it in a file on the disk.

In order to do this we need to decide on a file name. We have already discussed DOS files in Chapter 1. Recall that we can have eight characters for the file name and three characters for the file extension. Next we need to assign a file handle. For example, a for a file name "StudNames.Txt" could have a handle "students". Once we have decided on a file name we need to open this file either to read or to write. Now we can either read from this file or write to it depending on how it was opened. Once we are finished with reading or writing, we need to close the file.

A printer is considered to be a file; you can only write to it, can't read from it (output only). The keyboard also is considered to be a file; you can only read from it (input only). Files we create on disks or tapes can be used to read and write (input/output). Let us write a program to write some names to a file.

PROGRAM 3-2

Program FileDemo (input, TextFile);

{This program accepts a series of names and writes to file}

var

name : string[30];

nothing : char;

TextFile : Text;

begin

{friends.dta is the filename, TextFile is the handle}

{i.e. Pascal calls it TextFile, DOS calls it friends.dta}

assign(TextFile, 'friends.dta');

rewrite(TextFile); {Open this file to write}

{Now we are read to get the input and write to the file}

writeln('Instructions: Enter names of your friends. When');

writeln(' finished type QUIT.');

repeat

write('Name: ');readln(Name); {get input}

writeln(TextFile,Name); {write to file}

until Name = 'QUIT';

close(TextFile); {close the file}

writeln('All the names were written to the file!');

write('Type any key and press enter ');readln(nothing);

end.

Here is an example of the program run:

C:\TP>

Instructions: Enter names of your friends.

When finished type QUIT.

Name: JOHN

Name: MARY

Name: TOM

Name: WENDY

Name: SAM

Name: QUIT

All the names were written to the file!

Type any key and press enter

A

This program used a repeat..until loop structure that is covered in the next chapter. You may want to read ahead a chapter and then return to this program. The intention of this program is to demonstrate how to create and manipulate a text file. Make a note of the following steps:

1. In the program heading include all files used.

Program FileDemo(input, TextFile);

2. In the variable declaration section declare the file

as a type TEXT.

Var TextFile : TEXT;

3. Assign the Pascal identifier (handle) to DOS file.

Assign(TextFile, 'friends.dta');

4. Rewrite or reset the file (to write or read).

rewrite(TextFile);

5. When reading or writing to the file indicate so by its

name as the first parameter in the read or write statements.

writeln(TextFile, Name);

6. Close the file.

Close(TextFile);

The names you typed when you ran the program are saved in a file. You can view the contents of this file by using the DOS 'type' command which we discussed in Chapter 1. You can print this file by using the 'print' command which also was discussed in Chapter 1.

Earlier I mentioned that the printer is considered to be an output file. If you change just one line of the program, whatever you type will be printed on the printer. Here is the change:

Assign(TextFile, 'PRN');

Whenever possible you are encouraged to write output to a file instead of sending to the printer directly. After you have finished running the program, the output can be printed from the file using the DOS command "print". In the student lab there are several computers connected to one printer. If ten students were to send output to this printer, the output would have one line from one student, second line from the another student and so on. You will end up cutting and pasting output. This situation can be avoided by sending your output a file and then typing it out to the printer. Most instructors require you to turn in the program listing and program run one after on continuous sheets of papers. This can be easily accomplished if the program is in a file and the output is in another file. Suppose you have 'FileEx.Pas' as your program and 'Output.Dat' as your output. You can print these using this command:

copy FileEx.Pas + Output.Dat PRN

Stored information needs to be retrieved. In order to do this we need to open a file to read. Indicate the file name we are reading from as the first parameter of the read statement. And close the file when finished reading. Here is another program to retrieve the names that was stored in the file:

PROGRAM 3-3

Program FileDemo (input, TextFile);

{This program reads names that were stored in a file}

var

name : string[30];

nothing : char;

TextFile : Text;

begin

{friends.dta is the filename, TextFile is the handle}

{i.e. Pascal calls it TextFile, DOS calls it friends.dta}

assign(TextFile, 'friends.dta');

reset(TextFile); {Open this file to READ}

{Now we are read to read from the file}

writeln('Names read from the file:');

repeat

readln(TextFile,Name); {get input from file}

writeln(Name); {write to screen}

until Name = 'QUIT';

close(TextFile); {close the file}

writeln('All the names were read from the file!');

write('Type any key and press enter ');readln(nothing);

end.

Here is the run for this program:

C:\TP>

Names read from the file:

JOHN

MARY

TOM

WENDY

SAM

SANDY

QUIT

All the names were read from the file!

Type any key and press enter

This program needs some modification, it is not a good idea to show QUIT as a name. This can be handled by changing the order of reading, we will learn that later. The main difference between Programs 3-2 and Program 3-3 is the way the file is opened. In Program 3-3 "reset" was used. Reset opens the file to read whereas rewrite opens the file to write. The program keeps reading the names until "QUIT" is read.

Appendix 3A

IDENTIFIERS, VARIABLES AND DATA TYPES

IDENTIFIERS:

Identifiers and names that we use for different parts of the program are names we use to identify a memory location. You are free to use any names beginning with a character. You can use uppercase and lowercase letters, the underline character (_), and digits. You cannot use reserved identifiers (see below).

There are three categories of identifiers:

1. Reserved identifiers. Reserved words have special meaning to the compiler (examples: begin, program, case, procedure, end, etc.). You cannot use these reserved words for any other purposes. See complete list in the Turbo book that came the program you are using.

2. Standard identifiers. These also have predefined meanings, but you may re-use them. Examples are: EOF, Real, Sqr, Read, Input, etc.

3. User defined identifiers. These are the ones you make up. When you make up an identifier check the list of reserved and standard identifiers; don't use them.

VARIABLES:

Suppose you have a post office box (with a Box number - ADDRESS). You can only put one piece of mail in it at a time. If you put another one, the old one drops off. One can say that this box holds VARIABLE pieces of mail! The mail can be first class, second class or third class - different TYPES. The post office puts mail in your box because the box number is recorded on the mail. So when we talk about a variable, we know it has a name (an address), it has a value (a piece of mail), and a type (first class, second class, and so on). Higher level languages such as Pascal allow us to use names for variables, instead of memory addresses. The only requirement is that the compiler must know the type of data that will be placed. This is the only way the compiler can allocate enough memory locations for each variable. You can't expect to place a parcel containing a microwave oven in a standard mail box!

EXAMPLE: Tax_Rate := 7.0

The NAME of the variable is Tax_Rate. (It has 6 bytes set aside in memory on a PC -- because it is a real variable).

The VALUE (what is placed inside the memory locations) is binary equivalent of 7.0.

The TYPE of the variable is Real.

It is important that you understand these three distinct characteristics of a variable.

DATA TYPES:

Data types can be defined by the programmer. For convenience sake Pascal has provided you with some pre-defined data types. They are:

1. INTEGER - These are whole numbers; it takes two

bytes of memory to store an integer on a PC. The range of numbers an integer can handle is from -32768 to 32767 on the PC's you will be using. Turbo Pascal provides for larger integers through a type called LONGINT.

2. REAL - Real numbers are represented by numbers containing a decimal point (floating-point numbers). Real numbers occupy 6 bytes in memory. Examples of real numbers are: 6.0 341.33412341 1.0E-38.

3. CHAR - CHAR is used to hold ASCII characters. It takes one byte.

4. STRING - A string value is a sequence of CHARs (up to 255 separate characters).

5. BOOLEAN: A BOOLEAN value can be either TRUE or FALSE. It occupies only one byte.

 

ASSIGNMENTS FOR CHAPTER 3

1. Identify the different parts of the program 3-1.

2. A program is different from its run. Looking at the

Program 3-1, write down how the program run would look like. When doing this assume a blank paper is the monitor screen. Start writing what you will be seeing on the screen. Use a different colored pencil to indicate entries you make. Compare this with an actual program run. It is important that you know the difference between a program and the program run. You need to repeat this exercise several times with different programs until you feel that you can differentiate between the program and the program run.

3. Practice writing simple programs like:

a. Print Hello world on the screen.

b. Ask for the name of the user, and say hello.

c. Calculate the amount of sales tax for a sale.

4. Modify Program 3-2 and Program 3-3 to store and retrieve telephone numbers with the names.


Go to top of this chapter

Site design/development provided by the UTPA NewMedia Center
@1999 The University of Texas-Pan American