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 2
( Introduction to Turbo Pascal
)
Suppose you want to add two
numbers together. A program to do this should have the
following three steps:
1. get two numbers [input]
2. add these numbers [process]
3. show the sum [output]
The computer terms for these three steps are input, process and output.
Let's write the necessary instructions, in fact a computer program,
to do this.But, 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 the Appendix 2A
at the end of this chapter. Just to refresh your memory,
the commands are:
cd \tp <Enter>
turbo <Enter>
OR
Click on the
TURBO PASCAL ICON.
|
From the Menu choose
Edit. Type in the program as follows:
PROGRAM addition (input, output);
uses wincrt;
VAR
firstNumber, secondNumber : integer;
sum : integer;
BEGIN
write('Enter the first number to add ');
readln (firstNumber);
write('Enter the second number to add ');
readln(secondNumber);
sum := firstNumber + secondNumber;
write ('The total for these two numbers is:');
writeln(sum);
end.
|
After it is all typed in check it over for errors.
Save your program and exit. If you are using DOS version,
Press F2 key to save the program. Give it an appropriate name such as
B:PROGRAM1.PAS (assuming your disk in B: drive).
Now that you learned how to get into Turbo Pascal,
write a program and save it, it is time to learn how to
retrieve a file you saved. Just for practice, get out of Turbo
Pascal:
A ) Press F10 key
B ) Choose File
C ) Choose Exit
Now get back into Turbo Pascal and open the file you just saved.
Turbo Pascal brings up the program you
saved earlier. A program is a set of instructions for a computer to
carry out. Now we need to tell the computer to carry out these
instructions; choose main menu by pressing F10, then choose Run. If
you typed in everything correctly, a new screen will appear asking
you enter the first number. If there are errors in your program, you
will receive appropriate messages. Fix these bugs and Run it again.
If you typed in everything correctly, it will ask you for the first
number. Give it a whole number. It will now prompt you for the second number.
Give it another whole number. There you have it, the program gave you the
sum of these two numbers.
Program run:
Enter the first number to add 125
Enter the second number to add 5123
The total for these two numbers is: 5248
PROGRAM EXPLANATION
Let's 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 tell Pascal that we are going to be using
keyboard for input and
monitor for output. In other words, you are going to type in the
numbers using the keyboard, and the result will be displayed on the
monitor.
Next there is a
VAR section.
This is where
you tell Pascal the names of the variables you would
be using. A variable is a name of a memory location where the
number you type in would be stored. (If you didn't follow that,
please read the appendix 3A at the end of Chapter 3). In this
program three variables are used, firstNumber, secondNumber, and
Sum. All these variables belong to the same TYPE called integer
(whole number). We just told Pascal we would be using only whole
numbers, not fractions.
The next section is enclosed in the
BEGIN END pair. Thissection should be self explanatory.
These are the instructionsneeded to read two numbers, total them
and display the sumon the screen.
EXPLANATION OF PASCAL WORDS OR SYMBOLS USED
Since it is our first program, we have
used a lot of new Pascal words and symbols. We will look at them
very briefly here and will deal with them again at later
chapters.
PROGRAM
This is a reserved word to be used at the beginning of a program.
You cannot use this word in any other way within a Pascal Program.
()
Among other things, parentheses are
used to pass arguments to a procedure. For example, WRITELN is a
procedure; what you want to print on the screen is the argument, and
it is enclosed in the parentheses. Another example..Writeln ('Good
Day'); here 'Good Day' is the argument.
;
A semicolon is used separate two pascal statements.
VAR
This is another reserved word to be
used to declare the variables you would be using in a program or
procedure. Variable declarations are explained in Appendix
2A.
:
A colon is used to indicate types of variables declared.
BEGIN
Begin and End pairs are used to enclose
END
The End statements between them. These statements are then considered
to be a unit or a block. You can use as many of these as you wish,
as long as they are paired. You can have a Begin/End pair inside another
Begin/End pair (nested).
:=
This is an assignment operator.Whatever is on the right of this symbol
is assigned to the variable on the left of this symbol.
Temp := 78 will assign 78 to Temp.
write
This is a procedure. You can use this to write results on
the screen or into a file.
writeln
Same as write, except, writeln
will add a line feed and a carriage return. In other words, if you
use writeln, after writing a line the cursor will go to the
beginning of the next line. Whereas the write statement keeps the
cursor at the end of the current line.
read
read procedure is used to receive
input from the keyboard or from a file.
readln
When using a keyboard, both read and readln work the same unless you
give special compiler directives. When using a file, readln will read the
current variable and skip the rest until the end of the line
marker.
More
about read and readln:
Read
and Readln procedures allow the user to input data into the program
through a file or a keyboard. The main difference between these is
the position of the marker after execution of the statement. (When
using the keyboard read and readln works exactly the same unless
special compiler directives are given). The following examples
assume that the input is from a data file.
Example:
var
Year, Month, Day : integer;
--------------------------------------------
position comment
Readln(Year); 1982
█ marker on next
line.
Read(Year); 1982█ marker on
same line.
Readln(Year, Month, Day); 1989 2 13
█ marker on next
line.
Write
and Writeln procedures also work similarly. Write procedure does not
insert a carriage return and line-feed after execution, while
writeln does. Here are some examples of how the combination of read,
readln, write and writeln procedures work:
Readln(Year); 1982 You entered 1982
Writeln('You entered ',Year);
█
Readln(Year); 1982 You entered
1982█
Write('You entered ',Year);
Write('Do ');
Write('you '); Do you understand?
Writeln('understand?');
█
When
printing numbers, you can specify the number of spaces they should
occupy. If the number is longer than spaces specified, then Pascal
takes the necessary spaces. If the number is shorter then it is
padded with spaces on the left. With real numbers, the number of
decimal spaces that should appear on the output can be specified.
Remaining decimals are rounded. Writeln (result:8:2); specifies that
a total of 8 spaces will be allowed for the number including the
decimal point. The whole numbers will be right justified and the
fractional part will be aligned (left justified) with the decimal
point. Writeln (result:1:2) will indicate to allocate two decimal
places, but to left justify the whole number. Even though only one
space is allocated for the whole number, Pascal would take required
number of spaces to fit the whole number. But Pascal would not take
any more spaces for decimal places than those allocated.
Example:
Given
the following variables:
var
Age :
integer;
Weight
: real;
B :
Char;
Readln
(Age,Weight,B); 40 130.5 a
Writeln (Age:8); ^^^^^^40
(spaces are indicated with^)
Eight
spaces are allocated to write the value of age. Since age only
requires 2 positions six spaces are added to the left. In another
words age (40) is printed right justified!
Writeln (Weight:10:2); ^^^^130.50
Writeln (Age:1); 40
Total
of ten spaces are allocated to write the value of weight, two of
which will be used for decimals, one will be used for the decimal
point. So we have 7 spaces left to write the whole number portion of
weight (130), which is printed right justified. However, in the next
writeln statement, age is allocated one space. Since 40 cannot be
written in one spaces, pascal takes the additional space necessary.
This is a way to left justify a number.
Writeln ('Age is: ',Age:4); Age is: ^^40
Writeln ('Statement is ',B); Statement is a
Writeln (Weight:1:2); 130.50
Writeln ('Age ':6,Age:1); ^^Age 40
Everything inside the single quotes are considered to be
character (string) literals. Everything inside the quotes will be
printed exactly. If there are some characters without any quotes
enclosing them they would be considered to be a variable identifier.
Whatever the value of that variable is, that would be printed. You
can also print literals also in a specified number of spaces. See
example ['Age ':6] Age will printed in six positions. Notice this
includes a space within the quote. Therefore, there are four
characters to print, remaining two positions will be filled with
blanks.
If any
of the explanation above was difficult to follow, don't worry. We
will talk about most of these later or they are covered in the
appendix.
Appendix 2A
TURBO PASCAL
Pascal
is a high level structured programming language developed by
Nicklaus Wirth in the early seventies. Turbo Pascal has added many
enhancements to the original Pascal language by Wirth. Turbo Pascal
has gone through several versions, the most recent one at the time
of this writing is version 6.0.
Turbo Pascal package
comes with a powerful editor which is similar to the Word-Star's
non-document mode. The compiler will allow you to compile the
program to a file on a disk or to RAM. If compiled to the RAM you
can run the program without leaving the Turbo Pascal environment.
While running the program Turbo Pascal shows you the line of the
program if error occurred.
STARTING TURBO PASCAL.
Turbo Pascal is installed in a subdirectory called TP or PASCAL.
You can find out where it is by asking for a directory from the root.
If it is in the TP subdirectory do the following:
CD\TP PRESS <ENTER> ( this changes default to TP)
TURBO PRESS <ENTER> ( this loads the program )
At the top of the screen five menu options are given:
File, Edit, Run, Compile and Options.
Use arrow keys to choose an option. Each Menu has pull-down sub-menus.
For example if you wish to start writing a program you should be in
the edit mode. Use the right arrow to highlight Edit and then press enter.
You are now in the editor.
Once in the editor you can start typing your
program. When finished writing the program press ^KD (press K while
holding down the control key). If you wish to save the program
choose the File option and choose the Save option. It will show the
default file name NONAME.PAS and ask you to give it another name.
Review the section on HOW TO NAME A FILE in
Chapter 1. Once
saved in a file, you can load the program back in to memory by
choosing the Load option form the File menu.
Try all other menu options to see how they work. It is a good idea to
become thoroughly familiar with all options before getting into
heavy programming.
To
quit Turbo Pascal choose the Quit option from the File menu.
The
pull down menu under option FILE provides many powerful features.
Load, Save and OS shell will be discussed here. If you already have
a file created and want to edit it, just load it. Choose Load and
then type in the file name you want to load. If you do not remember
the complete file name, you can give wild card characters. Example
lab?????.pas or lab?????.*. The asterisk here stands for 3 question
marks. *.* stands for ????????.??? (also known as global or
star-dot-star).
The OS
shell provides a way for you to temporarily go to the DOS and
execute any DOS command you wish. Then you may return to where you
left off by typing EXIT. This powerful feature allows you to
examine, print or create files from DOS.
WRITING YOUR SECOND PASCAL PROGRAM
1 ) Change default working directory to Turbo Pascal
(Try cd\tp, if it does not work, ask lab assistant
for help!).
2 ) Type TURBO and press <ENTER>
3 ) Using arrow key highlight Edit and press <ENTER>
4 ) Type the following program:
PROGRAM
2-2
{This program converts height in inches
to centimeters and weight in pounds to kilograms}
Program Metrics (input, output);
Const
CentimetersPerInch = 2.54;
KilogramsPerPound = 0.45359;
Var
Inches,
Centimeters, Pounds, Kilograms : real;
begin
{convert}
write ('Enter
your height in Inches: ');
readln
(Inches);
Centimeters :=
Inches * CentimetersPerInch;< /FONT>
Write ('Enter
your weight in pounds: ');
readln
(Pounds);
Kilograms :=
Pounds * KilogramsPerPound;< /FONT>
writeln ('Your
height in centimeters is ', Centimeters:
7:2);
writeln ('Your
weight in kilograms is ',Kilograms:7:2);
end.
{Convert}
|
Program run:
Turbo
Pascal Version 6.0 Copyright (c) 1983,90 Borland International
Enter
your height in Inches: 65
Enter
your weight in pounds: 125
Your
height in centimeters is 165.10
Your
weight in kilograms is 56.70
Type
EXIT to return to Turbo Pascal...
Microsoft(R) MS-DOS(R) Version 5.00
(C)Copyright Microsoft Corp 1981-1991.
C:\TP>
5.
Press ^KD (Press K while holding control key and press D). Instead,
you can press F-10.
6 ) Press F (for file). Notice this has the same effect as using
the arrow key. Place a formatted disk in
drive B:. Save what you typed using the save option. Give it a file name, say,
B:METRICS.PAS.
7 ) Press R (to run the program) or use arrow key to highlight Run and
press <ENTER>. When this
option is chosen, the program is compiled and run without leaving
the Turbo Pascal environment.
8 ) While the program is running pressing F5 (Function Key 5) will zoom
window that is running the
program.
9 ) If you wish to get a listing of the program, go to edit mode and press
^KP. Or you can print the saved
file using one of the DOS commands
described in Chapter 1.
10 ) If the program did not run, you may have typed it wrong. The arrow keys
can be used to pilot the
cursor to the error position. You need to learn Turbo Pascal's
Editing Commands.
The commands are similar to Word Star.
MORE ON TURBO PASCAL COMMANDS.
Insert
: When you first enter Turbo Pascal, it is in the insert
mode.
This means whatever you type between two words will be inserted
there pushing the word on the right forward. You can get into
typeover mode by pressing the Ins key (or Control V).
Delete: Delete the character the cursor is on ---> ^G
Delete
one word to the right of the cursor ^T
Delete
the whole line--------------------> ^Y
Block:
Go to the beginning of the section you want to block and
press
^KB, then go to the end and press ^KK. Now you can do a lot of
things with this block. If you wish to move it, go to the location
you want to move it to and press ^KV (or ^KC to copy). If you wish
to write the block to a file press ^KW. To delete a block press
^KY.
Merge a file
: Suppose you have a subroutine saved in a file and
want
to merge it with a program you are currently writing, you can use
^KR. Then it will ask for the filename you want to read
in.
Turbo Pascal
5.0 provides you with a set of hot keys (Press just one key instead
combination ^KD etc.). Here are some :
F1 -
HELP
F2 -
SAVE CURRENT PROGRAM
F3 -
LOAD A FILE
F5 -
MAKE THE WINDOW YOU ARE WORKING WITH LARGER - ZOOM
F6 -
SWITCHES TO ACTIVE WINDOW
F10 -
CALLS THE MAIN MENU
You
can also use the Alt- and a key combination. For example, Alt-E to
get into the editor, Alt-R to run the program, Alt-F to get into the
File option, etc.
ASSIGNMENTS FOR CHAPTER 2
1 ) Modify Program 2-1 to add three numbers instead of two. Make
sure to modify the write statements
to reflect this change.
2 ) Add the following comments into the modified program at the appropriate
places:
{This program accepts three numbers entered
from the keyboard, sums these numbers, and prints
the result}
{Accept three numbers}
{Sum these numbers}
{print the results to the monitor}
>
3 ) Write a program to convert Fahrenheit to Celsius. Use Program 2-2 as
a guide.
>
4 ) Add appropriate comments (see assignment #2
above, use it as a guide) to Program 2-2.
Go to top of this chapter
|