TURBO-LESSONS - A Pascal TutorialVersion 1.01
TURBO-LESSONS
A TURBO Pascal Tutorial Version 1.01
by Lyle M. Faurot June 8, 1985
Copyright (C), 1985 by Lyle Faurot.All rights reserved.
TURBO is a trademark of Borland International.
TURBO-LESSONS - A Pascal TutorialVersion 1.01
T A B L E O F C O N T E N T S
Introduction . . . . . . . . . . . . . . . . . . . . . . .4 Distribution Notice. . . . . . . . . . . . . . . . . . .5
TURBO-LESSON 1: GETTING STARTED Loading TURBO . . . . . . . . . . . . . . . . . . . .5 Main Menu . . . . . . . . . . . . . . . . . . . . . .5 TURBO-LESSON 2: EDITING PROGRAMS Starting an edit session. . . . . . . . . . . . . . 10 Ending an edit session. . . . . . . . . . . . . . . 11 Moving the cursor . . . . . . . . . . . . . . . . . . PROG2 Inserting/Replacing text. . . . . . . . . . . . . . PROG2 Deleting text . . . . . . . . . . . . . . . . . . . . PROG2 Auto-tabbing. . . . . . . . . . . . . . . . . . . . PROG2 TURBO-LESSON 3: PROGRAM STRUCTURE Program structure . . . . . . . . . . . . . . . . . . 12 Compiler Directive, $U+ . . . . . . . . . . . . . . . 13 WRITE and WRITELN statements. . . . . . . . . . . . 13 Comments. . . . . . . . . . . . . . . . . . . . . . 14 TURBO-LESSON 4: DECLARATIONS, INPUT DECLARATIONS part of program. . . . . . . . . . . . 16 VAR declaration . . . . . . . . . . . . . . . . . . . 16 Input usint READLN statement. . . . . . . . . . . . 17 Integer Variables . . . . . . . . . . . . . . . . . . 18 TURBO-LESSON 5: INTEGER EXPRESSIONS Assignment statements . . . . . . . . . . . . . . . . 20 Integer expressions . . . . . . . . . . . . . . . . . 21 Problems with expressions . . . . . . . . . . . . . . 23 TURBO-LESSON 6: CONDITIONAL PROCESSING Selection structures. . . . . . . . . . . . . . . . 25 IF statement (One-way selection). . . . . . . . . . 26 IF statement (Two-way selection). . . . . . . . . . 27 TURBO-LESSON 7: REPEAT STATEMENT CHARacter variables . . . . . . . . . . . . . . . . . 28 BOOLEAN variables . . . . . . . . . . . . . . . . . . 29 REPEAT statement. . . . . . . . . . . . . . . . . . 30 TURBO-LESSON 8: CASE STATEMENT Block statements. . . . . . . . . . . . . . . . . . 32 CASE statement. . . . . . . . . . . . . . . . . . . 34 TURBO-LESSON 9: FOR STATEMENT Print field width indicator, ":n" . . . . . . . . . . 36 FOR statement . . . . . . . . . . . . . . . . . . . . 37 TURBO-LESSON 10: WHILE STATEMENT CONSTant declaration. . . . . . . . . . . . . . . . 38 WHILE statement . . . . . . . . . . . . . . . . . . . 39 Delay timing loop . . . . . . . . . . . . . . . . . . 41
When Borland International ran their first ads for TURBO PASCAL my reaction was "You gotta be kidding - they can't do that".But, it seems they did!I've been enjoying this programming system ever since.Apparently a great many other programmers are either programming in TURBO or would like to learn how.TURBO-LESSONS were designed to meet that need.
Each TURBO-LESSON is a bite-size tutorial which introduces one or more new concepts.Each of the lessons are presented in the same format which includes the OBJECTIVES of the lesson, and the TUTORIAL portion of the lesson.Most lessons direct you to work with a sample program which is provided with these lessons.
Be sure you make a back-up copy of the programs - you will be modifying and adding to the sample programs, and may want to return to the original copy of a program.
Sample programs are numbered to correspond to the lessons: PROG1 goes with TURBO-LESSON 1, PROG2, PROG2A go with TURBO- LESSON2, . . .
To begin, you should print the TURBO-LESSONS before loading TURBO.To help you get started, TURBO-LESSON 1 shows you how to load TURBO and run a sample program.
Suggested donation, $7.00, for this first set, lessons 1-10, may be sent to:
Dr. Lyle Faurot 1904 18th Ave. South Moorhead, MN 56560
Clubs and other non-profit organizations may copy these lessons for their members, with the following conditions:
No charge is made for TURBO-LESSONS, except a distribution charge may be made to cover the price of the diskette.Suggested donation is to be made directly to the author of the lessons.
Club members are informed that TURBO-LESSONS are distributed as user-supported software.
TURBO-LESSONS are distributed unmodified.
TURBO-LESSONS were written with the following goals in mind:
Present the concepts of Pascal and the TURBO Pascal implementation in bite-size chunks (called lessons).
Provide one or more sample Pascal programs with each lesson. Programming examples are often more helpful than eloquent discussion in learning to program.
Structure the lessons in a parallel format to make them more useful later as a reference.The OBJECTIVE section at the beginning of each lesson will help you locate a topic later.
Structure the lessons in an Action format.If you are like me, you probably learn programming best by doing.
Mark the points where some action is suggested.This should allow for differences in learning styles.The action points are marked as follows:
##### DO:
For those who like to hit the high points as fast as possible, these action markers will point the way.
Now, without further delay, on with the show!
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 5
1.Loading TURBO.
To get started, put a diskette with TURBO PASCAL in your default drive.
Type TURBO and enter.
A message will appear:
Include error messages (Y/N)?
You should answer Y to provide on-screen error messages.The Main Menu will appear at this point.
2.Using the Main Menu to Load, Compile, and Run a program.
The menu should appear with one letter of each option highlighted.
Adjust the brightness level of your screen.You may need to adjust both brightness and contrast to make the key letters stand out at a comfortable level.
The main menu is the starting point for most of the things you will do with TURBO.Some of the options will be discussed in more detail later, but for now, you should learn to get back to the main menu from each of the options.
******************** Logged drive:
The Logged drive is where your Work files are stored.This option is used to change your logged drive.
Type L.
Computer responds: "New drive:"
Type B (or another drive) and enter.
Look at the top of the screen.Did the logged drive change?
Now, depress the space bar.It appeared that no change had been made until the menu screen was redisplayed.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 6
******* NOTE:SOME OF THE OPTIONS DO NOT UPDATE THE MENU SCREEN. YOU CAN REDISPLAY THE MENU WITH THE SPACE BAR OR ENTER KEY.
You could have responded to the "New drive:" message by depressing the enter key without entering another drive designator.The enter key by itself is used to escape from this option without making any changes.
The first four options at the top of the menu, L, A, W, and M all use the enter key alone as an escape key.
******************** Active directory:
Use the A option to change the Active subdirectory if your logged drive is a hard disk.
Type A.
Computer responds: "New directory:"
Type subdirectory name and enter or just enter for no change.
******************** Work file:
This is where you name your work file.The work file will hold the PASCAL program you are writing or editing.
Type W.
Computer responds: "Work file name:"
Type PROG1 and enter. (If you get the message, "New File", PROG1.PAS was not found on your logged drive. Your sample programs, including PROG1, should be on the logged drive).
******************** Main file:
Ignore this option for now.If you just can't resist typing M at this point, remember that Enter is the escape key for this option.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 7
******************** Run
This option is used to execute a program, compiling it first, if necessary.
Type R.
The program in your work file, PROG1, is compiled and executed.
Type R again.
Note that the program runs again without compiling.The Run option will only compile if changes have been made in the program since the previous compile.
Depress the space bar to get the menu back.
******************** Compile
The program may be compiled without executing by using the C option.You may want to compile to see an error message without running the program.Or you may be compiling a COM file, which cannot be executed until you exit TURBO to DOS.
Type C.
The program compiles but doesn't run.Use this option when you want to compile without executing the program immediately.
******************** Edit
The editor is used to enter a new program or change a program. Another lesson is devoted to editing.For now, you should find out how to get back to the menu from this option.
Type E.
The program, PROG1, appears on the screen, ready to edit. Use the Ctrl-K, Ctrl-D sequence to return to the main menu.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 8
Type Ctrl-K, Ctrl-D. (While depressing the Ctrl key, type K followed by D.)
The main menu reappears.Note that there is no way to abandon the edited file in memory.This is not so bad since the edited copy of the program in memory is not automatically saved to disk. You can use the Work file option to get another copy of the program from disk.
******************** Save
Use this option to copy your current work file from memory to disk.
Type S.
The program, PROG1, is saved to the disk on the drive designated when you named this work file.Since the work file is not automatically saved to disk, TURBO reminds you to save the file before any option which would destroy the copy of the file in memory.
NOTE: REMEMBER, IT IS UP TO YOU TO SAVE YOUR WORK FILE.IT'S A GOOD IDEA TO SAVE IT FREQUENTLY, IN CASE SOMETHING SUCH AS AN INFINITE LOOP FORCES YOU TO RE-BOOT (IN WHICH CASE YOUR WORK FILE IN MEMORY WOULD BE FOREVER GONE!)
******************** Dir
The D option works similar to DIR in DOS.
Type D.
Computer responds: "Dir mask:"
Depress the Enter key to get a directory of the logged drive or use drive designator to get a directory of another drive.You can use the wildcards, "*" and "?".
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 9
******************** compiler Options
These will be discussed later when they are needed.Try the O option now to be sure you know how to get back to the menu.
Type O.
The compiler Options menu is displayed.
You can choose the various compiler options by typing the corresponding letter.
Type C.
Notice the arrow moved to a different option.
Type H.
Type M.
Be sure to leave the compiler option set to M, memory before returning to the main menu.
Type Q.
The main menu reappears.
******************** Quit
This option returns you to DOS.When you are through experimenting with the menu options,
Type Q.
You will be prompted to save your work file if it has been modified since you last saved it.The prompt of the default drive will be displayed.
LESSONS - A Pascal TutorialVersion 1.01Page 10
TURBO-LESSON 2: EDITING PROGRAMS
OBJECTIVES - In lesson 2 you will learn about:
1.Starting an edit session 2.Ending an edit session 3.Moving the cursor to desired location 4.Inserting/replacing text 5.Deleting text 6.Auto-tabbing for readable programs
TURBO-LESSON 2 uses a slightly different approach than most of the other TURBO-LESSONs.Much of the tutorial material of this lesson is in PROG2.PROG2 is not really a program, but a tutorial itself.After starting the editor with PROG2, you will learn to edit by editing PROG2 in ways suggested within the "program".
******* NOTE: BE SURE YOU HAVE A BACK-UP COPY OF THE TURBO- LESSONS AND SAMPLE PROGRAMS.MANY OF THE LESSONS WILL DIRECT YOU TO MAKE CHANGES IN THE PROGRAMS.A BACK-UP COPY WILL PROVIDE A NEW COPY OF THE ORIGINAL PROGRAMS WHENEVER THEY ARE NEEDED.
1.Starting an edit session.
There are two ways to start an edit session.One way is to invoke the editor yourself when you wish to write a new program or modify an old one.The other way is automatic.When TURBO compiles your program and finds an error, it switches to the edit mode by itself and highlights the probable error.More about that later.This lesson covers only the first method.You start an edit session by typing E at the main menu.
Type E.
Computer responds: "Work file name:".
Type PROG2.
PROG2 will appear on the screen with the Editor "status line" at the top of the screen.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 11
2.Ending an edit session.
One of the first things you learn when learning to drive a car is how to stop. When editing a program, you need to know how to get out of the editor and back to the main menu.To exit the editor and save the edited file, type ctrl-k followed by either d or ctrl-d.(Ctrl-k means: hold down the control key while depressing k).Note that the editor has no provision for abandoning an edited file - if you need to abandon a file, exit the editor and reload the work file from disk without first saving the edited version.
Type ctrl-k, d.
Computer responds: Main menu.
Type E.
Computer responds: Edit session is started with PROG2.
After working through the tutorial contained in PROG2, you may want to load and run PROG2A.PROG2A prints the cursor movement reference table referred to in the tutorial.To run PROG2A:
Type W.
Computer responds: "Work file name".
Type PROG2A.
Type R.
PROG2A executes, printing a short summary of the cursor movement keys used by the TURBO editor.
TURBO-LESSON 3:PROGRAM STRUCTURE
OBJECTIVES - In this lesson you will learn about:
1.Program structure 2.Compiler Directive, $U+ 3.Write and WriteLn statements 4.Comments - at beginning of program 5.Comments - at end of statement line 6.Comments - kill a section of code temporarily
1.Program structure.
PASCAL programs are written in a certain way to make them easier to write and easier to read.There are two parts to any PASCAL program: the DECLARATIONS part and the PROGRAM BODY.
The PROGRAM BODY is where the processing statements occur, and any data item used there must first be defined in the DECLARATIONS section.The form of a PASCAL program is
PROGRAM Demo; (Program name - not required) LABEL (Labels, if used, go here) CONST (Constants are defined here) TYPE(Define your own data types here) VAR (ALL variables must be defined here)
BEGIN (Processing statements occur between END. BEGIN and END.)
The simplest PASCAL program is:
BEGIN END.
Type in the program:
BEGIN END.
Exit the editor and type R to execute the program.
What happened?(If you hold the R key down to run the program over and over, you may see the message, "running").
Notice that no compile errors or run time errors occurred (evidenced by the absence of error messages on the screen).
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 13
Definitely not the most useful program, but it illustrates a point: the MAIN BODY is always required and as much of the DECLARATIONS section as needed to define the data used.Since this simple program uses no data,the DECLARATIONS section can be omitted.
Standard PASCAL requires that declarations occur in the order specified and each type of declaration may occur only once. TURBO is a little more forgiving in some respects than standard PASCAL (declarations don't have to occur in the specified order, and the same type of declarationmay occur more than once).
2.Compiler Directive, $U+
Compiler directives are used to control special features provided by the compiler.The directive, $U+, which occurs at the beginning of most of the sample programs, ensures that you will be able to stop a program without rebooting.
3.Write and WriteLn statements.
These processing statements are introduced first, because they can be used with messages which require no previous data declaration.This allows you to experiment with some programming in the MAIN BODY without any concern for the DECLARATIONS part.
Load PROG3 and use the editor to examine the program.A part of PROG3 is printed below:
BEGIN WriteLn('* * * * * * * * * * * * * * * * * ');{Note that comments} WriteLn(' *');{placed at the end of a} WriteLn('*TURBO-LESSON 3 ');{statement line should } WriteLn(' *');{be terminated on the} WriteLn('Edited, Compiled, Executed by');{same line.A multiline } WriteLn('* (put your name here)');{comment, like the one at} WriteLn(' ');{the beginning of this } WriteLn(' * * * * * * * * * * * * * * * * *');{program would include } {some of the non-comment statements, making them ineffective. }
In this section of PROG3, the WriteLn statement is used to display messages.
RUN the program to see the messages displayed on the screen. (Ctrl-K, Ctrl-D to exit editor, then R to run the program.Refer to lessons 1 and 2 and your reference manual for more help using TURBO and the editor.)
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 14
Use the editor to insert your name in the line indicated and run the program again.
To illustrate the difference between WriteLn and Write statements, another portion of the program is included below:
WriteLn; Write('Check carefully when '); Write('you run this program. '); Write('How many lines '); WriteLn('are printed'); WriteLn('by this last set of Write and WriteLn statements?');
The "Ln" in WriteLn may be viewed as a linefeed or "return the cursor to the beginning of the next line".Note that the instruction is WriteLn, not LnWrite.The order is significant. Any message, or other data item within the parentheses following WriteLn is printed first, the "Write" part, then the cursor is moved to the next line, the "Ln" part.
Notice the first WriteLn in the program segment above.There is nothing in parentheses to print, so this statement is a way to print a blank line.
The next three Write statements write on the same line.Then the following WriteLn statement writes it's message and causes the cursor to return to the beginning of the next line.
The last WriteLn displays it's message on the line where the cursor is positioned, and returns the cursor to the next line.
Add some WriteLn statements after the BEGIN to insert several blank lines at the top of the screen to push the boxed message down the screen.
Run the program.Did it work right?
4.Comments - at the beginning of program.
There are two ways to indicate comments in a PASCAL program.The curly brackets, { }, may be used to enclose comments.The original comment delimiters, from standard PASCAL are (**).
At the beginning of a program, or anywhere that multiple line comments are needed, it is convenient to mark the whole block of comments with the delimiters at the left margin. This makes it easy to insert or delete comments within the block.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 15
Add some comments at the beginning of the program. Try both types of comment delimiters, { }, and (* *).
5.Comments - at the end of a statement line.
Look at the comments following the WriteLn statements in PROG3. Short comments may be inserted to clarify the action of one or more statements.NOTICE CAREFULLY that each of these comments has to be completed on the same line, if the next line is another active processing statement.
Add a short comment, {Blank Line}, after one of the WriteLn statements which prints a blank line.
6.Comments - kill a section of code.
Having two sets of comment delimiters makes it possible to use one set for most comments, while reserving the second set for "killing" sections of statements when debugging a program.
I prefer to use the { } for most comments, and (**) for killing code.You should keep the delimiters used for commenting out (killing) code in the left margin where they are very visible.
Kill the three WriteLn statements following the one which prints TURBO-LESSON 3.
Run the program to see the results.
DON'T BE AFRAID TO EXPERIMENT WITH THE SAMPLE PROGRAMS.YOU CAN ALWAYS GET ANOTHER COPY, FROM YOUR BACKUP DISK (you did make one, didn't you), FROM THE .BAK FILE PROVIDED BY TURBO, OR FROM THE ORIGINAL FILE IF YOU HAVEN'T SAVED AN EDITED COPY.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 16
TURBO-LESSON 4:DECLARATIONS, INPUT
OBJECTIVES - In Lesson 4 you will learn about:
1.The DECLARATIONS part of a program 2.VAR declaration 3.Input using the ReadLn statement 4.Integer variables
1.The DECLARATIONS part of a program.
You learned in the previous lesson that there are two main parts to any PASCAL program: DECLARATIONS, and MAIN BODY. The various entries in the DECLARATIONS section define the data items used in the processing in the MAIN BODY.Not all declaration entries will occur in every program, but only the ones needed to support the processing.
The various types of declaration entries will be introduced as needed in the sample programs.Only the VAR entry will be used in this program.
2.VAR declaration.
All variables, (spelled A-L-L, no exceptions), must be defined before they are referenced by processing statements.The VAR entry is used to define variables.The form of the entry is:
variable-name :type;
The variable-name may be one or several variable-names separated by commas.The type may be a predefined type, such as Integer, or a type you have constructed useing the predefined types. The colon must occur between the variable-name(s) and the type. Extra spaces are acceptable to allow more readable format.Below are some VAR entries:
VAR i,j,k: Integer; Inkey: Char; Rate : Real; Count: Integer;
(The example above includes types not yet discussed, to illustrate the form of the VAR entry.)
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 17
Look at PROG4.
(You know from earlier lessons how to load the program and use the editor to look at the program.)A segment of PROG4 is:
VAR Number : Integer;
The VAR entry above defines a variable called "Number" to be of type "Integer".This means the computer must set up a memory location large enough to store an integer, which can be accessed by referring to the name "Number".
Notice the variable, Number, is later referenced in the processing statements.
Add an integer variable called "Age" to Prog4.This will be used later in this lesson.You can either add the new variable to the declaration of Number
Number, Age : Integer;
or add another declaration
Number : Integer; Age: Integer;
Compile the program to be sure you haven't made a syntax error.
3.Input using the ReadLn statement.
ReadLn is the statement used to input variables.The form of the statement is:
ReadLn(var_1, var_2, . . . ,var_n);
When the statement is executed, the computer will wait for you to type values for the variables, separated by one or more spaces, followed by depressing the enter key.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 18
Part of PROG4 follows:
BEGIN Write('Enter a number (no decimals please): '); ReadLn(Number); WriteLn;{ Display one blank line } WriteLn('Number: ',Number); { Display the number entered } END.
The Write statement provides a prompt before the ReadLn accepts Number.Notice that ReadLn does not provide a "?" or any other prompt.The programmer must provide any prompting require.
The use of the Write statement for prompting, instead of the WriteLn, keeps the cursor on the same line so the input will occur right after the prompt message.
The ReadLn accepts the number you type and stores it in the memory location which the computer has set aside for the Integer variable, Number.
Compile and run PROG4.When prompted, type 12 and enter.Run it again and enter -34.
Using the statements of PROG4 as an example, expand the program to do the following:
(1) Write a prompt to 'Enter your age'. (2) Read a value for age to be stored in the integer variable, Age, which you added to the VAR declarations in the previous section. (3) Write a message which prints the age entered, in a manner similar to the way Number was printed.
Run the program.
4.Integer Variables.
Integers are counting numbers, with no decimal points.They may be positive or negative.In TURBO the range of Integers permitted is:
-32768 to +32767
Integers are used for subscripts, indexes, counting, input and output of such things as counts, limits, menu choices.Decimal numbers (Real type, discussed later), are needed for such things as dollar amounts and calculations. When decimal numbers are not actually needed, Integers should be used since they are easier to use and take less memory.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 19
Run PROG4 again, this time entering data which will cause errors.
When prompted to enter a number, enter the letter A instead. What happened?
A message appears:
I/O error 10, PC=287C Program aborted
Searching 15 lines
Run-time error position found. Press
What this means is as follows:
The program aborted because "I/O error 10" occurred at program code address, 287C.(Your program may produce a different program code address.)To find out what "I/O error 10" is, look in your reference manual in the appendix containing "I/O ERROR MESSAGES".Error 10 is an "Error in numeric format".
TURBO searched 15 lines before finding where the error occurred.
When you press the ESC key, the editor is activated with the cursor positioned at the end of the statement which caused the error.(In this case, it is not the statement which caused the problem, but the type of data entered.)
Run the program again, entering too large a number, 88888.Note that the same error occurs.Run it again with too small a number, -55555.You may want to experiment with the end-points of the acceptable integer range: -32768 to 32767.For example, try entering the values -32767, -32768, -32769.
NOTE: THERE ARE WAYS TO HANDLE ERRORS TO AVOID ABORTING THE PROGRAM.MORE ABOUT ERROR-HANDLING IN LATER LESSONS.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 20
TURBO-LESSON 5:INTEGER EXPRESSIONS
OBJECTIVES - In lesson 5 you will learn about:
1.Assignment statements 2.Integer expressions 3.Problems with expressions
1.Assignment statements.
A large part of computer processing is accomplished by storing numbers, strings, and other data objects in memory locations in the computer. There are several ways to store a value in memory in Pascal: (1) use an Input statement (ReadLn), (2) use an Assignment statement, (3) use a Procedure or function.
The Assignment statement has the following form:
Variable := Expression;
An example: A := B + C;
The way it works:The computer evaluates the expression on the right side of the replacement operator, :=, and stores the resulting value in the memory location named by the variable on the left.
In the example above, the computer would obtain whatever value is currently stored in the memory location called B, add that value to the value it finds in the memory location called C, and store the sum in the memory location, A.If B holds the value 3, and C holds the value 4, then 7 would be stored in the memory location called A.
Use the editor to enter the following short program (omit the comments, if you like):
PROGRAM ABC;
VARA, B, C: Integer;
BEGIN A := 6;{Assign the value 6 to the memory location, A} B:=7;{Assign 7 to B } C := A + B;{Add the values in A and B, Store in C } WriteLn ('A=',A, ' B=',B, ' C=',C); END.
Run the program.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 21
Note that you have just written a complete PASCAL program - from here on, you will just be adding new features in each lesson to enable you to write more complicated programs.(It didn't run? Use the error message to correct any errors.If the error message doesn't make sense, try looking for misplaced or omitted semicolons.Also note that the assignment statement uses the compound symbol, ":=" and not "=".).
2.Integer Expressions.
Integer expressions are composed of integer variables, constants, and operators.The operators used with integer expressions are: +, -, *, div, mod.
The + and - have their usual meaning, addition and subtraction. The * indicates multiplication. Division of integer numbers is done with div and mod.
Examine at PROG5.
Two numbers, which you enter, are added, subtracted, and one is cubed using the multiply operator, "*".WriteLn is used to print out the results.
Notice that expressions may be calculated in an assignment statement, I_Cubed := I * I * I;
or calculated in a WriteLn statement,
WriteLn('I - J', I - J);
Run the program.
Note that the ReadLn statement will attempt to read 2 values. The values should be typed with a space between, not a comma.
Enter the values 2 and 5.
Check all the results.Are they all correct?
Run the program again, this time entering -3 and 5.
Is everything correct again?Notice the negative cube of -3 is as expected, -27.(Some incorrect negative cubes will appear a little later in this lesson.)
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 22
The division operators, div and mod are not used in PROG5.To see how they work,
Just before the END of PROG5, edit in the following statements:
WriteLn('I div J = ', I div J); WriteLn('I mod J = ', I mod J);
Run the program, entering the values 5 and 3.
Did you get the results expected? Is 5 divided by 3 really 1 and not 1.666?
Add these two statements at the end of the program:
WriteLn(I,' divided by ', J, ' = ', I div J); WriteLn(' with a remainder of ', I mod J);
Run the program with the values 5 and 3.
Often, when working with integers, it is useful to know one or both of these components of the division.If you really want the decimal result of the division, the slash, /, could be used with integers.
Add this statement at the end of the program:
WriteLn('I / J = ', I/J);
Run the program with the values 5 and 3.
Note the result of division using the slash is the usual result.
Before going on, try adding a few WriteLn statements to the program to improve the readability of the output.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 23
3.Problems with expressions.
You should be aware of the possibilities for various types of errors involving expressions.First, an easy to detect error.
Declare K to be an integer variable.
Add these statements at the end of the program:
K := I / J; WriteLn('K = ', K);
Run the program.How did it go?
This error, "Type mismatch", is easy to find, since the compiler finds it.The reason for the type mismatch is that the result of the division using the "/" is a real number (covered in a later lesson).The variable, K, is an integer.A real number can't be stored in an integer memory location.(Why not?One reason: a real number takes 3 times as much memory space.)
A second type of error, is illustrated in the following:
Run the program using the values 31 and 5.
Check the results of the cube of I.Is it correct?
O.K., but notice the cube of I, 29791, is approaching the upper limit of integer variables, 32767.
What will happen if you enter 32 and 5?(The correct cube of 32 is 32768, just 1 too large to fit as an integer.) Try it!
Run the program using the values 32 and 5.
The computer, known for its reliability, informs you:
The cube of I = -32768
Now, you know the sign is wrong - positive numbers do not produce negative cubes.But look at the number, -32768.Correct number with the wrong sign?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 24
Run the program again with the values 33 and 5.
The cube of I = -29599
Wrong number!Wrong sign!So why does the computer go merrily on its way - giving you these wrong answers?
The computer is very good at detecting errors in the format of program statements, missing declarations, wrong punctuation. There are other types of errors that are more difficult to detect.
It is up to you, the programmer, to find ways to keep these errors from going unnoticed.For now, you need to be aware that these problems can occur.Error detection will be covered in later lessons. TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 25
TURBO-LESSON 6:CONDITIONAL PROCESSING
OBJECTIVES - You will learn, in this lesson, about:
1.Selection structures used for conditional processing 2.IF statement(one-way selection) 3.IF statement(two-way selection)
1.Selection structures used for conditional processing.
There are three types of statement sequencing used in PASCAL:
(1)SIMPLE SEQUENCE.One statement follows another with no branching.
(2)SELECTION STRUCTURES.Based on a condition, supplied by the programmer, the next statement to execute is chosen from two alternatives (IF statement) or chosen from many alternatives (CASE statement).
(3)REPETITION STRUCTURES.A group of program statements may be repeated more than once, dependent on a condition supplied by the programmer.The repetition statements are WHILE, REPEAT, and FOR, included in later lessons.
The Selection statement, IF .. THEN .. ELSE, is illustrated in this lesson,the CASE statement appears in a later lesson.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 26
2.IF statement (one-way selection).
The one-way IF is really a special case of the two-way IF, where the second alternative is to do nothing, just go on to the next statement.The form of the IF statement is:
IF condition THEN statement;
The condition is an expression or comparison which the computer can evaluate as TRUE or FALSE.Examples of a condition:
7 < 10TRUE I < 10TRUE, if the memory location named I holds a value less than 10, otherwise FALSE. NOT(7 < 10) FALSE (7 < 10 is TRUE, but NOT reverses the value to FALSE).
Look at PROG6.
The first IF statement is a one-way selection.If the condition is true, the WriteLn statement will be executed.If the condition is false, the WriteLn will be ignored.
Run the program using 0 for the no of computers owned.
Run it again with 1 for the no of computers owned.
The "No Computer!" message should print for 0 computers owned, but not print for 1 computer owned.
Examine the last IF in the program.
This is a one-way IF with a slightly more complicated condition. The condition contains an integer expression, (Want - Have).The computer first evaluates the integer expression to get a number to compare with the 2 on the right side of the ">".
Run the program several times with different input to see the effect of this IF.
Also note the misspelled "Aren''t" in the message.The double apostrophe is used in the message to represent a single apostrophe.If a single apostrophe were used, it would appear to be the end of the message.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 27
3.IF statement (Two-way selection).
The two-way IF causes one of two alternative statements to be executed, based on whether the condition is TRUE or FALSE.The form of the statement is:
IF condition THEN Statement_1 ELSE Statement_2;
If the condition is TRUE, the statement following the THEN is executed.If the condition is FALSE, the statement following the ELSE is executed.
Look at the second IF in PROG6.
This is a two-way IF.A congratulations message is printed if the condition is true,condolences if false.
The condition is (Have >= Want).This condition is true if the number you enter for computers owned is greater than or equal to the number you enter for computers you would like to have.
Run the program several times, experimenting with various input values.
Try your hand at writing an IF statement to do the following:
If the number of computers owned is more than the number of computers wanted, print a message 'Send extra computers to (put your name here?) '. TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 28
TURBO-LESSON 7: REPEAT STATEMENT
OBJECTIVES - In lesson 7 you should learn about:
1.CHARacter variables 2.BOOLEAN variables 3.REPEAT statement
1.CHARacter variables.
The reserved word, CHAR, is used to declare a variable of character type.A variable of type CHAR can be used to refer to or store a single character.
VAR Alpha : CHAR;
Alpha is declared to be a variable which can be used to store any of the characters in the character set.This includes the upper and lower case alphabet, the digits, 0 to 9, special characters such as #, $, %, *, and the rest of the 256 characters in the PC's character set.
Examine PROG7.
A variable named Response, of type CHAR, is used to store the character entered in response to a multiple choice question.
Run the program several times, entering wrong responses, and the correct response, D.Also try lower case d.
Study the first IF statement in PROG7.
IF (Response = 'D') OR (Response = 'd') THEN . . .
The character 'D' must be enclosed in single quotes in the program.Note that you enter the character as input data without quotes when running the program.
Notice the compound condition using OR to combine two simple conditions.This condition will be true if eitheror both of the simple conditions are true.The correct response, D, is checked in both upper and lower case to make responding easier.
Modify the IF statement to accept A, B, or C as the right response. Assume that the correct answer is A or B or C.(Ignore lower case responses to keep the statement short.)
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 29
2.BOOLEAN variables.
BOOLEAN variables can have only two values, TRUE or FALSE. The value of a condition, TRUE or FALSE, may be stored in a BOOLEAN variable for later use.
VAR Correct_Response : Boolean;
In PROG7, the Boolean variable, Correct_Response, is used to store the truth value (TRUE or FALSE) of the condition in the first IF statement.If the correct character, 'D' or 'd', is entered, TRUE is stored in Correct_Response.If anything else is entered, FALSE is stored.
Actually, TRUE and FALSE are stored as 1 and 0 to take up less space, but you can always view a BOOLEAN variable as having a value of TRUE or FALSE.
Identify the condition in the second IF statement in PROG7.
Since BOOLEAN variables can only have two values, TRUE or FALSE, and conditions always evaluate to the same two values, a BOOLEAN variable may be substituted for a condition.
If would be permissible, but unnecessary to write the IF statement:
IF Correct_Response = TRUE THEN . . .
Modify the IF statement as indicated above and run the program to verify that the IF still works exactly as before.
There is another way to assign the correct value to the variable, Correct_Response.
Replace the FIRST IF statement in PROG7 with the following statement:
Correct_Response := (Response = 'D') OR (Response = 'd');
Run the program.
How does the program change when you run it?(If it doesn't do exactly as before, maybe you typed it wrong, or replaced the second IF instead of the first?)
Since the condition on the right of the := must be evaluated by the computer and assigned a value of TRUE or FALSE, this value can be stored directly in a BOOLEAN variable without using the IF statement.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 30
3.REPEAT Statement.
In a previous lesson, you learned that there are three ways to sequence the execution of statements in PASCAL: SIMPLE SEQUENCE, SELECTION STRUCTURES, and REPETITION STRUCTURES.
One of the statements used for REPETITION is REPEAT . . UNTIL. The form of the REPEAT statement is:
REPEAT Statement 1; Statement 2; . . . Statement n UNTIL condition;
Statements 1, 2, . . . , n will be executed repeatedly until the condition becomes true.This implies that the condition is checking something that can be changed by the statements 1 to n. If this is not so, the statements will be repeated forever!
In PROG7, you are prompted to respond to the multiple choice question.A REPEAT statement controls the block of statements which prompt for a response, and then check the response.The block of statements will be repeated until the UNTIL condition is true.
Change the condition in the UNTIL in PROG7 to:
UNTIL 'A' = 'B';
Run the program.
Does the program correctly identify a correct response?What happens then.
(Use ctrl-c or ctrl-Scroll-Lock to stop the program.)
Change the condition again to:
UNTIL 'A' = 'A';
How many times are you prompted for a response?
Notice that the statements in a REPEAT structure are ALWAYS executed at least once.Even if the UNTIL condition is TRUE before entering the REPEAT, the condition is not checked until the end of the statements in the REPEAT block.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 31
Try to find another way to terminate the REPEAT without using the BOOLEAN variable, Correct_Response, in the UNTIL condition.
Hint: Check the statement which assigns a value of TRUE or FALSE to Correct_Response. TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 32
TURBO-LESSON 8: CASE STATEMENT
OBJECTIVES - In lesson 8 you will learn about:
1.Block statements 2.CASE statement
1.Block statement.
As noted in an earlier lesson, the form of the IF statement is:
IF condition THEN statement_1 ELSE statement_2;
IF the condition is true, statement_1 is executed, otherwise statement_2 is executed.However, a single statement may not always get the job done.
The Block statement (also called a Compound statement) allows you to substitute a multiple statement block anywhere a simple statement is acceptable.The form of the Block statement is:
BEGIN Statement_1; Statement_2 END;
You can include as many statements as you like between the BEGIN and END.
Notice that the main body of a Pascal program is a single statement!That single statement is a block statement:
BEGIN Statement_1; Statement_2; . . . Statement_n; END.
To illustrate the use of a Block statement in an IF statement, consider the following problem:
If the value of I is greater than the value of J, swap the two in memory (a common problem when sorting data).
If you happen to have a single statement to swap the values of two memory locations, the IF statement might be:
IF I > J THEN SWAP(I,J);
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 33
Later, you will learn how to make up your own "statements" (by creating functions and procedures), but for now, the way to swap I and J is:
IF I > J THEN BEGIN Temp := I; I := J; J := I; END;
Notice that the form of this IF statement is still correct:
IF condition THEN statement;
The statement, in this case, is a Block statement, rather than a simple statement.
Take a look at the program called TEST1.
The sample programs which begin with the word TEST are provided to make it quicker for you to test new statements and concepts. The program, TEST1, has some integer variables and character variables declared and the main BEGIN END.All you need to do to test a statement, or group of statements, is edit them into the test program and run the program.
Insert the following statements between the BEGIN and END of program TEST1:
Write('Enter two numbers '); ReadLn(I, J); WriteLn('I=', I, ' J=', J);
Run the program.
Between the ReadLn and WriteLn statements you just entered, add the IF statement to swap I and J if I is larger:
IF I > J THEN BEGIN Temp := I; I:= J; J:= Temp; END;
Run the program several times using several pairs of input numbers to test the program.Does the "swap" work right?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 34
Remove the BEGIN and END in the IF statement and run the program several times.
Does the "swap" still work right?
Without the BEGIN and END to make the three statements appear as one,the statements "appear" as follows to Pascal:
IF I > J THEN Temp := I; I := J; J := Temp;
Only the statement, Temp := I, is controlled by the IF condition.
2.CASE statement.
First, a bit of review from an earlier lesson:
Program sequencing is done in Pascal with
(1) Simple Sequence, one statement follows another,
(2) Selection Structures, IFfor one-way and two-way selection, CASE for many-way selection,
(3) Repetition Structures, REPEAT statement, WHILE statement, FOR statement.
The CASE statement is useful when there are more than two actions or statement sequences needed.The form of the CASE statement:
CASE variable OF value_1: Statement_1; value_2: Statement_2; . . . value_n: Statement_n; ELSE Statement; END; {CASE}
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 35
Note the following:
The variable must be a simple type such as Integer, CHAR, BOOLEAN. (REAL is not allowed).
The values used to determine which Statement to execute must be of the same type as the variable.
The values may be a constant, a list of constants, or a subrange such as 1..10 (all integers from 1 to 10).
How it works:
If the variable has a value of "value_1" then Statement_1 is executed.If "value_2" then Statement_2, . . .
If the value of the variable matches none of the values, the statement following the ELSE is executed.
There must be an END to mark the end of the CASE statement. (It's a good idea to add the comment {CASE} after the END).
Use the editor to examine PROG8.
This is the same problem as in the previous lesson, with a bit more programming flexibility derived from the CASE statement and the block statements.
Notice that the list of variables in the CASE statement allow appropriate responses for acceptable responses: A, a, B, b, C, c correct responses: D, d unacceptable responses: anything else.
Modify the CASE statement in PROG8 to accept C as the best answer.
Run the program.Did it work?
What message appears when D is entered? TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 36
TURBO-LESSON 9: FOR STATEMENT
OBJECTIVES - In lesson 9, you will learn about:
1.Using ":n" to specify field width in Write statements 2.FOR statement
1.Using ":n" to specify field width in Write statements.
Spacing of output in previous lessons has been done using spaces in string constants, such as, 'I= '.The space after the = will be printed as part of the string.
There is another way to add spaces.When listing the items to write in a Write or WriteLn statement, ":n" can be added to specify how many characters the item is to occupy in the output.
For example:
WriteLn(I:4);
The value of I would be printed in a space 4 characters wide.
Run Program TEST1 several times with the following statements in the main part of the program:
ReadLn(I); WriteLn('[', I:4, ']');
Look closely at the output.Are the numbers "left-justified" or "right-justified"?
If I has a value of 23, and 23 prints in columns 1 and 2 of the 4 column field, it is left-justified.If the 23 appears in columns 3 and 4 of the 4 colunm field, it is right-justified.
What happens if you enter a number that is too large to fit the field specified?
Run the program several times using the following values for I:
123, 1234, -1234, 12345
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 37
2.FOR statement.
In the previous lesson, you were reminded of the various ways to control the sequencing of program actions.One of the REPETITION structures is the FOR statement.The forms of the statement are:
FOR variable := lowvalue TO highvalue DO Statement; {May be a block statement with BEGIN END}
FOR variable := highvalue DOWNTO lowvalue DO Statement;
Run PROG9 several times to see how it works.
Experiment with both positive and negative numbers.
What happens if High is smaller than Low?
Run PROG9 using 5 for the Low, 3 for the High?
What was the result?
Also try 5 for both values.How many times is the loop repeated if Low = High?
What results would you expect if you entered 3.4 for Low and 5.3 for High?
Run the program with the values 3.4 and 5.3.
Were you correct in predicting the outcome?
Can constants be used instead the variables Low and High?
Edit the FOR statement in PROG9 as follows:
FOR Index := 1 to 5 DO
Run the Program.
Is it possible to use expressions for Low and High?
Change the FOR statement to:
FOR Index := Low + 1 TO High DO
Run the Program. TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 38
TURBO-LESSON 10: WHILE STATEMENT
OBJECTIVES - In lesson 10 you will learn about:
1.CONSTant declaration.
In the declaration section of the Pascal programs in previous lessons, only VAR and PROGRAM have appeared.
CONST is used to declare constants and assign values to them. The form is:
CONSTConstant_Name_1 =Value_1; Constant_Name_2 =Value_2; . . . Constant_Name_n =Value_n;
Some examples:
CONSTPI=3.14159; Fahr_Freeze =32; Cels_Freeze =0; Message_1 ='This is a string constant';
Run PROG10 a time or two to see what it does.
Edit the constant declaration, Wobble_Size = 5; toWobble_Size = 10;
Run the program.What effect did you see from the change?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 39
Change the value of Left_Edge to 20 and run the program.
To understand how Left_Edge and Wobble_Size work, look at the WriteLn statement:
WriteLn(': ':Left_Edge,First:Index,Last:2,Message);
(1)': ' is printed in the right 2 columns of a field whose width is determined by the value of Left_Edge.
(2) First initial is printed in the rightmost column of a field of width, Index.Note that Index is changing in the FOR loop, so the width of this field changes.
(3) Last initial is printed next in the rightmost column of a 2-character wide field.
(4) The string constant, Message, is printed immediately to the right of Last initial.
Run the program several times with the values of the constants reset to various values.(LIVE DANGEROUSLY - try some wild values:50 for Wobble_Size or 70 for Left_Edge.Your CRT won't explode!At least mine hasn't - yet!)
2.WHILE statement.
The three Pascal REPETITION Structures are: (1)WHILE (2)REPEAT (3)FOR
The form of the WHILE statement is:
WHILE condition DO statement;
Note that the statement is often a block statement and appears:
WHILE condition DO BEGIN Statement_1; Statement_2; . . . Statement_n; END;
The WHILE is executed "while" the condition is true.
Contrast the REPEAT which is executed while the condition is false, UNTIL the condition becomes true.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 40
Run PROG10 again, using 0 as the number "less than 8".
How many times was the loop executed?
You could substitute REPEAT for WHILE in PROG10.
Replace: WHILE Count > 0 DO with: REPEAT
add: UNTIL Count = 0; after: END; {WHILE}
(Notice that you don't have to remove the BEGIN END when you change the loop from WHILE to REPEAT.They are not needed in the REPEAT statement, but a block statement is always acceptable wherever a simple statement can be used.)
Run the program several times to verify that it still works the same as with the WHILE loop.
Run the program with 0 for the "number less than 8".
How many times was the loop executed?
Notice that the WHILE loop may be executed 0 times, but the REPEAT loop is always executed at least once, since the condition is not checked until the end of the loop.
NOTE: YOU SHOULD BE ON THE LOOKOUT FOR SUCH CONTRASTS BETWEEN "INTERCHANGEABLE" STATEMENTS.CHOOSING THE BEST STATEMENT TO USE IN EACH CASE IS BASED ON THIS KIND OF AWARENESS.
Change the REPEAT loop back to the original WHILE loop. (An easy way would be to load a fresh copy of the original PROG10.)
Change the WHILE statement to accept only Last initials less than 'G'.
WHILE Last < 'G' DO
Run the program. How did it work?
The WHILE loop didn't terminate at all - you had to abort the program, right?(If it is still executing, use Ctrl-C or Ctrl- Scroll-Lock.)
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 41
One of the things needed in controlling loops: something in the loop must be related to the condition.
In the original WHILE loop, the Count was being decreased in the loop.
When the condition was changed to (Last < 'G'), the loop no longer has any effect on the condition.
Either the loop will not be executed at all, if Last is = or > 'G', or it will execute indefinitely if Last is < 'G'.
Change the WHILE statement to:
WHILE (Last < 'G') AND (Count > 0) DO
Run the program several times using last initials before and after G in the alphabet.
Run the program with last initial of 'a' (lower-case a).
How many times did the loop execute?
Why?
The ASCII value of 'G' is 71.The ASCII value of 'a' is 91.So 'a' is > 'G'. (More on how to handle this problem in a later lesson.)
3.Delay timing loop.
You may have noticed the "wobble" proceeds faster in one direction than the other.This is due to a timing delay in the first WHILE loop.
FOR Delay := 1 to 500 DO; {Do nothing, except loop}
This looks a little strange? There should be a statement after the DO?
Pascal has a "null" statement for just such times as this.When a statement is required, but none is present, Pascal just substitutes its "null" or "do-nothing" statement.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 42
Change the delay in the loop from 500 to 2000 and run the program.
Add a timing loop to the other WHILE loop and run the program.
How did it work?
You didn't forget to add BEGIN END when you added the delay statement, did you?
One last little twist on timing loops:
Change the Wobble_Size to 10.
Change both delay statements to:
FOR Delay := 1 to 500 * Index DO;
Run the program.Note that delays don't have to be constant. This delay varies as the FOR loop progresses!
NOTE: I HOPE YOU HAVE ENJOYED THESE FIRST 10 TURBO-LESSONS.YOUR COMMENTS AND SUGGESTIONS WOULD BE WELCOME!
TURBO-LESSONS
A TURBO Pascal Tutorial Version 1.01
Set # 2 - Lessons 11 - 17
by Lyle M. Faurot June 27, 1985
Copyright (C), 1985 by Lyle Faurot.All rights reserved.
TURBO is a trademark of Borland International.
INTRODUCTION TO TURBO-LESSONS
When Borland International ran their first ads for TURBO PASCAL my reaction was "You gotta be kidding - they can't do that".But, it seems they did!I've been enjoying this programming system ever since.Apparently a great many other programmers are either programming in TURBO or would like to learn how.TURBO-LESSONS were designed to meet that need.
Each TURBO-LESSON is a bite-size tutorial which introduces one or more new concepts.Each of the lessons are presented in the same format which includes the OBJECTIVES of the lesson, and the TUTORIAL portion of the lesson.Most lessons direct you to work with a sample program which is provided with these lessons.
To begin, you should print the TURBO-LESSONS before loading TURBO.
D I S T R I B U T I O NN O T I C E
TURBO-LESSONS are being distributed as USER-SUPPORTED software.
Suggested donation, $5.00, for this second set, lessons 11-17, may be sent to:
Lyle Faurot Box 494 Moorhead, MN 56560
COPYING BY ORGANIZATIONS
Clubs and other non-profit organizations may copy these lessons for their members, with the following conditions:
1.No charge is made for TURBO-LESSONS.A distribution charge may be made to cover the price of the diskette.
2.Club members are informed that TURBO-LESSONS are distributed as user-supported software.
3.TURBO-LESSONS are distributed unmodified.
T A B L E O F C O N T E N T S (Set # 2,Lessons 11 - 17)
Page
Introduction Distribution Notice
TURBO-LESSON 11: INTRODUCTION TO FUNCTIONS Pascal subprograms. . . . . . . . . . . . . . . . . 50 * FUNCTION declaration. . . . . . . . . . . . . . . . 50 User-defined function . . . . . . . . . . . . . . . . 51
TURBO-LESSON 12: FUNCTION APPLICATION - ERROR DETECTION Error detection . . . . . . . . . . . . . . . . . . . 55 Using a predefined function . . . . . . . . . . . . . 56 Writing your own function . . . . . . . . . . . . . . 58
TURBO-LESSON 13: STRINGS Strings . . . . . . . . . . . . . . . . . . . . . . . 60 String replacement statement. . . . . . . . . . . . 60 Predefined string function, LENGTH. . . . . . . . . 63
TURBO-LESSON 14: INTRODUCTION TO PROCEDURES PROCEDURE declaration . . . . . . . . . . . . . . . . 65 Using a procedure . . . . . . . . . . . . . . . . . . 66 Using parameters. . . . . . . . . . . . . . . . . . 67 A counter with error checking . . . . . . . . . . . . 68
TURBO-LESSON 15: INTERACTIVE SCREEN HANDLING Setting up a data entry screen. . . . . . . . . . . 70 Being nice to users - ClrScr. . . . . . . . . . . . 71 Getting around the screen - GotoXY. . . . . . . . . 72 Screen messages and accepting user input. . . . . . 73
TURBO-LESSON 16: REAL NUMBERS Range of real numbers . . . . . . . . . . . . . . . . 74 Input/Output of real numbers. . . . . . . . . . . . 75 Calculations with real numbers. . . . . . . . . . . 76 Calculations with integers and real numbers . . . . . 78
TURBO-LESSON 17: A TIMING FUNCTION Include files . . . . . . . . . . . . . . . . . 79 A timing function . . . . . . . . . . . . . . . . . . 80 Improving timing accuracy . . . . . . . . . . . . . . 81 Sources of errors in timing . . . . . . . . . . . . . 82
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 50
TURBO-LESSON 11: INTRODUCTION TO FUNCTIONS
OBJECTIVES - In this lesson, you will learn about:
1,Pascal Subprograms 2.FUNCTION declaration 3.User-defined function
1.Pascal Subprograms.
The example programs in earlier lessons have been rather small. As programs grow in size and complexity, it is essential that you utilize the appropriate tools to simplify the programming effort.
The subprogram is one of the most powerful tools for simplifying a complex program.Subprograms may be viewed as "building blocks" for constructing programs.
As you learn to write Pascal programs, you will find Pascal subprograms rather easy to write - they are almost identical to programs!
There are two types of subprograms in Pascal: FUNCTIONS and PROCEDURES. Both types may be either user-defined (written by you) or pre-defined as a part of Pascal.
In this lesson you will work with a user-defined FUNCTION.
Most of what you learn about FUNCTIONS also applies to PROCEDURES.
2.FUNCTION declaration.
Below is a simplified structure of a Program, Function, and Procedure:
PROGRAM FUNCTION PROCEDURE LABEL LABELLABEL CONST CONSTCONST TYPETYPE TYPE VAR VARVAR
FUNCTION(s) FUNCTION(s)FUNCTION(s)(0 or more FUNCTIONS) PROCEDURE(s)PROCEDURE(s) PROCEDURE(s) ( and PROCEDURES)
BEGIN BEGINBEGIN (processing (processing(processing statements) statements)statements) END.END; END;
Notice that they look very similar.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 51
One difference, visible here, is the END of the processing block: A period follows the END of a PROGRAM block, but a semi-colon follows the END of a FUNCTION or PROCEDURE block.
3.User-defined function.
Examine FUNCTION Cube in PROG11 using the editor.
FUNCTION Cube(Number:Integer) : Integer;
The FUNCTION declaration above means:
FUNCTION Type of subprogram, a FUNCTION, not a PROCEDURE.
Cube The name of the FUNCTION.
Cube must be assigned a value by one of the statements in the FUNCTION BEGIN END block.
(Number:Integer) An integer "parameter" called Number is used within the FUNCTION.
This is the number to be cubed.
: Integer; Type of value to be assigned to Cube.
Study the connection between the following two statements:
In FUNCTION Cube:
FUNCTION Cube(Number:Integer) : Integer;
In PROG11:
WriteLn('The cube is: ', Cube(No) );
Cube(No) in the statement above invokes (calls) the FUNCTION Cube to operate on the number called No.
PROG11,No ----->Number, in FUNCTION Cube.
The value of the variable called No in PROG11 is provided to the FUNCTION to use as a value of its variable called Number.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 52
Determine how Cube obtains its value in the FUNCTION.
Cube := Number * Number * Number;
This statement cubes the value in the variable Number (which Number received from the variable, No, in the main program) and assigns the result to the FUNCTION name, Cube.
The WriteLn statement prints this resulting value in the position indicated by the reference to Cube(No) in the WriteLn list.
Run PROG11 several times using the following values for input:
3,-3,0
31 (cube should be 29791)
32 (cube should be 32768)Is it?Remember this problem from an earlier lesson?You will explore some techniques for detecting this problem in the next lesson.
Now, let's see what happens if you change some of the things in the FUNCTION and the reference to it.
What would happen if you used a constant instead of No in the reference, Cube(No)?
Change the WriteLn statement to:
WriteLn('The cube is: ', Cube(3) );
Run the program several times with different input values.
Do you get the same result no matter what you input?
Notice that the variable, No, which you input, is no longer used in the FUNCTION reference, Cube(3).
What about expressions in the reference to the function?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 53
Change the FUNCTION reference to Cube(No - 2).
Run the program several times with input values:
5 (No - 2) is 3, so cube should be 27.
1 (No - 2) is -1, so cube should be -1.
-1(No - 2) is -3, so cube should be -27.
Do integer expressions work o.k?
What if you tried to use a non-integer value in the Cube(No) reference?
Modify the WriteLn statement to:
WriteLn('The cube is: ', Cube('This is a string') )
Run the program.
Did the compiler complain?
Error 44: Type mismatch.
When you press ESC, the cursor stops at the offending reference.
The problem: 'This is a string' was given to the function to use as an integer value,but it is a string, not an integer.
A good way to learn to recognize errors, is to introduce one error at a time and check the results.
Let's look at some errors which you might make in setting up the FUNCTION itself.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 54
Change the type of Number to Char.The FUNCTION declaration should appear:
FUNCTION Cube(Number:Char) : Integer;
What happens when you attempt to run or compile the program?
Error 47: Operand type(s) does not match operator.
When you press ESC, the cursor stops, not at the line you modified, but at the line:
Cube := Number * Number * Number;
Why?
There is nothing wrong with the line you changed.It may not do what you want it to, but to the computer, it is just an Integer FUNCTION with a character for input.
The problem appears (to the compiler) when an attempt is made to multiply a character times a character in the line marked by the cursor.At this point the compiler alerts you to the problem.
DEBUGGING NOTE: DON'T FORGET, THE CURSOR POINTS TO THE PLACE WHERE THE ERROR WAS DETECTED BY THE COMPILER. THE CAUSE OF THE ERROR MAY BE ELSEWHERE!
What would happen if you inadvertently designated the function as something other than Integer?
Change the FUNCTION declaration to:
FUNCTION Cube(Number:Integer) : Char;
Run the program.What results did you get?
Error 44 again - Type mismatch.
Again, the cursor points to the calculation.
This time though, the calculation itself is o.k.The problem occurs when an attempt is made to assign the integer result to the Character FUNCTION, Cube.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 55
TURBO-LESSON 12: FUNCTION APPLICATION - ERROR DETECTION
OBJECTIVES - In this lesson, you will learn about:
1.Error detection 2.Using a predefined function 3.Writing your own function
1.Error detection.
In the previous lesson,you found that some input values caused a problem.The function used in PROG11 calculated the cube of a number entered.If the result was outside the range of valid integers (for this version of Pascal), a run-time error terminated the execution of the program - NOT A NICE EVENT!
If you write programs for others to use, you will have to deal with the problem of ERRORS.
There are several approaches to error handling:
(1) Error detection before it happens - prevent the occurrence of the error.
(2) Error detection when it happens - take corrective action.
(3) Ignore the error - let the program bomb!
The 3rd is not usually acceptable - but may be o.k. in the early stages of program development since you, the programmer, can fix the problem.You may also find alternate ways to program for the same result while avoiding the possibility of the error.
The 2nd, error detection when it happens, will be explored later. Input/Output errors are typical examples of this class of errors.
In this lesson, you will find ways to detect a problem and prevent its occurrence.
In PROG12, examine FUNCTION Cube.
The function has been expanded to detect integers which are too small or too large to produce a valid integer cube.If a number is entered which would cause an error, the result is set to 0 instead of the erroneous result.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 56
Run PROG12 several times using the following values for input:
3,-3,31, 32, -32, -33, 0
Were all the results as expected?The inputs,32 and -33, would produce cubes out of the range of valid integers, so these two should have given results of 0.
What about 0 as an input?Did you get the correct result?
Can you determine whether a result of 0 is valid(0 input) or invalid (input of < -32 or > 31)?
Later in this lesson you will write your own function to deal with this problem!
2.Using a predefined function.
Pascal provides many functions and procedures which are already defined.
Some advantages of using predefined subprograms:
(1)The subprogram is already debugged.
(2)The subprogram doesn't take up room in your program.
(3)You can spend your time on more interesting programming, no need to "reinvent the wheel".
To use a predefined function, you have to know:
(1)The name of the function
(2)What goes in(what values do you provide as input?)
(3)What comes out(what result is associated with the function name?)
The absolute value function, ABS, can be used in PROG12 to illustrate the use of a predefined function.
What goes inWhat comes out
3 --------> [ABS] --------> 3
-5 --------> [ABS] --------> 5
The absolute value function provides a positive number of the same magnitude as the positive or negative number input to the function.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 57
Add the following statement after the ReadLn(No) statement in PROG12:
WriteLn('Absolute value: ', ABS(No) );
Run the program several times with both positive and negative numbers.
NOTE: THERE ARE OFTEN SEVERAL WAYS TO DO THE SAME THING IN PROGRAMMING.YOU SHOULD BE LOOKING FOR WAYS TO DECIDE WHICH OF SEVERAL PROGRAMMING SOLUTIONS IS BETTER IN A GIVEN CASE.
The next two exercises demonstrate two ways to use ABS in the error detection problem.You should decide which of the two is better.(Maybe neither is better than the present form of PROG12).
Change the WriteLn with the reference to Cube to:
WriteLn('The cube is; ', Cube(ABS(No)) );
Test the program with various inputs to make sure the results are the same as before.
Is the sign correct on all cubes (using both positive and negative inputs)?
Try -32 as an input.What was the result? Why?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 58
Now, try another way to use the ABS function.
Restore the WriteLn to its original form:
WriteLn('The cube is: ', Cube(No) );
Also change the first line of the IF statement in the FUNCTION Cube to:
IF ABS(Number) > 31
Test the program with several values.
Did you get the same results as in the previous exercise?
Which way do YOU think is best?(Maybe neither because of the problem with -32?)
How would you decide whether to use the function, ABS, in the main program or in the function, Cube?
Is the action accomplished by ABS of interest to you in getting the cube of a number?If not, it should probably be pushed out of the main program and into the subprogram.
3.Writing your own function.
Now, it's your turn.Another approach to the error detection problem uses a second function, which you are about to write!
Give the function the name:Has_Valid_Cube
The function will have one input:Numberof type Integer
The type of the function will be:Boolean
What the function does:
If Number would produce a valid cube, the function, Has_Valid_Cube, will have the value, TRUE.
If Number would produce an error, Has_Valid_Cube will have the value, FALSE.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 59
Write the function, Has_Valid_Cube.Place it before the main program.It can be either before or after the function, Cube.
Look at FUNCTION Cube if you need help with the form of the function declaration or the IF statement needed.
In the main program, replace the WriteLn which references Cube with the following:
IF Has_Valid_Cube (No) THEN WriteLn('The cube is: ', Cube(No) ) ELSE BEGIN WriteLn('The cube of ',No,' is outside the integer range'); WriteLn('in this version of Pascal.'); END;
Test the program with several positive and negative values and values which would cause erroneous cubes.
(If you have trouble writing the function, PROG12A is available as a sample.Don't check PROG12A until you have given it a try on your own!)
Are there any other improvements you want to make to PROG12?
FUNCTION Cube still checks for invalid inputs.Is this still necessary?
Change FUNCTION Cube so that it does no error checking, just calculates the cube of the number input.
Test the program with several values including 0.
Note that there is no longer any ambiguity when the result is a cube of 0.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 60
TURBO-LESSON 13:STRINGS
OBJECTIVES - In this lesson, you will learn about:
1.Strings 2.String replacement statement 3.Predefined string function, LENGTH
1.Strings.
You have already seen some Pascal strings in the WriteLn statements of earlier lessons.
WriteLn('This is a string.');
It is often convenient to store strings as variables or constants.
A string constant may be defined in the CONST section:
CONST String_1='TURBO-LESSONS';
String variables must be declared in the VAR section.The form of the declaration is:
VARFirst_Name : String[12];
This sets up storage for a variable named First_Name which can store a string up to 12 characters long.
2.String replacement statement.
The replacement statement for strings is:
String_Name := (string expression);
Examine PROG13.Notice the following:
A string constant, S_Test is given the value 'Test String' in the CONST declaration section.
Several string variables are defined in the VAR section.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 61
Run the program.
What happens when an attempt is made to store too long a string in a string variable?
Add the following to the program:
S5 := S_Test; WriteLn(S5);
Run the program.
How many characters of S5 are printed?
Modify WriteLn(S5) to:
WriteLn('[', S5, ']');
Run the program.How many characters of S5 are printed?
DEBUGGING NOTE:When working with strings, you may find it helpful to print some kind of marker before and after a string to help "see" the occurrences of the character, blank.
You have seen what happens when storing 'Test String' in too short a variable:S3 holds 'Tes',S8 holds 'Test Str'.
What happens when a string is stored in a variable that is larger than needed?Are blanks added?
Modify the WriteLn(S14) to bracket S14 (like you did above with S5) and run the program.
How many characters of S14 were printed?
Were extra blanks added?(More on this later.)
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 62
Look at PROG13A.
WriteLn(S8[I]);
Notice the use of the square brackets in the statement above. This is a way to refer to a specific character in a string.
S8[2] means the 2nd character in the string, S8.
NOTE: SQUARE BRACKETS ARE USED IN TWO DIFFERENT WAYS WITH STRINGS.WHEN DECLARING VARIABLES, THE BRACKETS ENCLOSE THE MAXIMUM LENGTH OF THE STRING.IN PROCESSING STATEMENTS, THE NUMBER IN THE BRACKETS DESIGNATE A PARTICULAR CHARACTER IN A STRING.
Run the program, using 2 as position number.
Try 5 as an input.What character was stored as the 5th character of S8?
The string stored in S8, 'TURBO', is 5 characters long but S8 is 8 characters long.
What characters, if any, are stored in S8[6], S8[7], and S8[8]?
Run the program with input values of 6, 7, and 8.
What characters were printed?
Add the following statement as the first statement in the BEGIN END block:
S8 := '12345678';
Run the program again, using 6, 7, and 8 as input.
What do you conclude about "unused" positions in a string?
Before you are prompted to enter the "position number", S8 is printed.
Do positions 6, 7, 8 of the string print? Why?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 63
Run the program once more, this time use 0 as the input value.
What character printed?
If you look up this character, clubs symbol, in the ASCII chart in your BASIC manual, you find that it is the character associated with ASCII value 8.
String variables in TURBO are one character longer than the maximum length you specify.This extra character is at the beginning of the string, at position 0, and always contains the length of the string stored.
So why isn't the length stored as a number?
Storing the length information as a character makes position 0 the same type as the other characters in the string.
3.Predefined string function, LENGTH.
Because the length of a string is often needed in processing, the function, LENGTH, has been provided for that purpose.
Add the following statement after the UNTIL statement:
WriteLn('Length of string: ', LENGTH(S8) );
Run the program.
There is also another way to get the ASCII value of the character at position 0 of a string.
Add the following statement just before the END:
WriteLn('ASCII value: ', ORD(S8[0]) );
Run the program.
Does the ASCII value agree with the value obtained with the LENGTH function?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 64
Just before the END, insert:
FOR I := 0 to LENGTH(S8) DO WriteLn('Position ', I:2, ':',S8[I]);
Run the program.
Change the CONST declaration to:
S_Test = 'OK';
Run the program.
Also try 'Wake Up' for S_Test.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 65
TURBO-LESSON 14: INTRODUCTION TO PROCEDURES
OBJECTIVES - In this lesson, you will learn about:
1.PROCEDURE declaration 2.Using a Procedure 3.Using Parameters 4.A counter with error checking
1.PROCEDURE declaration.
The PROCEDURE subprogram is similar to the FUNCTION subprogram introduced in an earlier lesson. The form of the declaration is:
PROCEDURE Add(No_1, No_2 : Integer; VAR Sum : Integer);
BEGIN Sum := No_1 + No_2; END;
Add is the name of the Procedure.
No_1, No_2, and Sum are integer variables called "parameters".
VAR in front of Sum indicates that this parameter is a "two-way street".It can receive data from the calling program, and return data to the calling program.No_1 and No_2 can only receive data from the calling program.
The BEGIN END block defines the processing performed by the procedure:
Add the value in the memory location, No_1, to the value in memory location, No_2, and place the result in the memory location, Sum.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 66
2.Using a Procedure.
A reference to this procedure in the main program (or another procedure or function) would have the following form:
Add(2, Count, Adjusted_Count);
The procedure is "called" or utilized by simply using its name as a statement.(When you define a Procedure or Function, you are adding additional "statements" to your programming language.)
Notice that there are three "parameters" here, and three in the Procedure declaration.The three here are associated with the ones in the declaration by position.
The first parameter here, the integer, 2, provides input to the first parameter of the procedure, No_1.
The second, the variable, Count, provides input to the second parameter of the procedure, No_2.
The third, Adjusted_Count, provides input to the third parameter of the procedure, Sum.
Since Sum is declared VAR, variable, it also provides output back to Adjusted_Count.
In the Main Program In Procedure Add
2 ----------> No_1{ When Procedure} Count ----------> No_2{is called}
Adjusted_Count <---------- Sum { When Procedure ends }
Inspect PROG14.
Run the program.
Add the following statement as the first statement in the main program:
Sum := 10;
Run the program.
Does it make any difference what value is stored in Sum before Procedure Add is referenced?Look at the procedure - is Sum used as an input for the calculation, or only as a result?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 67
3.Using Parameters.
You have already been using parameters, but in this section, you will see a little more of the power and flexibility of parameters.
Change the Add statement in the main program to:
Add(2, 2, Adjusted_Count);
Run the program.Is the result as expected?
Change the Add to:
Add(Count, Count, Adjusted_Count);
Run the program. Any surprizes?
Change the Add to:
Add(2, 3, 4);
Run the program. What happened?
The compiler refused to accept 4 as a variable identifier.
The VAR preceding Sum in the procedure declaration puts a limit on the corresponding parameter in the calling program: it has to be a variable location to receive the value of Sum when the procedure finishes its calculation.
The first two parameters in the procedure, No_1 and No_2, are used only for input to the procedure - they do not provide any output back to the corresponding parameters in the calling program.
For this reason, the first two parameters in the calling program are less restricted.They can be constants, variables, or expressions, as long as they are of the same type, integer, as the corresponding parameters in the procedure.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 68
Change the Add statement:
Add(4, 2 * Count + 5, Adjusted_Count);
Run the program. Does the expression work o.k. as a parameter?
Change the Add to:
Add(Count, Count, Count);
Also change the WriteLn to print the value of Count instead of Adjusted_Count.
Run the program. Any problems?
4.A counter with error checking.
You could use the Procedure Add as a counter by using the following call:
Add(Count, 1, Count);
The procedure would add 1 to Count and put the result in Count.
You could accomplish the same thing with the statement
Count := Count + 1;
So why bother to use the procedure?
What if Count reaches the upper limit of the integer range, 32767?
In the main program you could expand the counting statement to:
IF Count < 32767 THEN Count := Count + 1 ELSE WriteLn('Counter reached upper limit');
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 69
PROGRAMMING NOTE: HOW DO YOU DECIDE WHAT GOES INTO THE MAIN PROGRAM AND WHAT TO PUT IN SUBPROGRAMS?
FROM THE FOLLOWING DISCUSSION, TRY TO FORMULATE AT LEAST ONE RULE FOR MAKING THIS DECISION.
This looks a little messy, maybe you should use a procedure to get this out of the main program.
Not a bad reason, but there's a more important reason:
Ask yourself, "How much of the processing in the IF statement above is of interest in the main program?"
Probably only the fact that a count is being incremented.The error checking and how it is done is probably of little interest and just clutters up the main program.
Write your own procedure to increment the counter, Count.
Call the procedure, Increment.
Check for the upper limit of the integer range.(The IF statement above would be one way.)
Note that only one parameter is needed, preceded by VAR.
In the main program, add the following to check out your procedure:
FOR I := 1 to 10 DO BEGIN Increment(Count); WriteLn('Count = ', Count); END;
Run the program using the following values as input for count:
0,3,-34, 32760
(PROG14A is provided in case you need help.)
You could also write a procedure, Decrement, to decrease a counter.Note that the error checking would be checking the lower limit, -32768, or perhaps 0 depending on how you intended to use the counter.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 70
TURBO-LESSON 15:INTERACTIVE SCREEN HANDLING
OBJECTIVES - In this lesson, you will learn about:
1.Setting up a Data Entry Screen 2.Being nice to users - ClrScr 3.Getting around the screen - GotoXY 4.Screen messages and accepting user input
1.Setting up a Data Entry Screen.
For most computer processing applications you will need to provide for entry of data.This is one of the points where your programs interact with the person using the program.
How your programs are viewed by those using them will depend on how well you manage the user-computer interaction on the screen.
In this lesson you will try some of the basic techniques of screen handling for data entry.
Run PROG15.
Take a look at the program to see how this screen was produced.
Experiment with PROG15.
Run the program after each of the following:
(1)Add or delete spaces in the WriteLn statements to move the various items.
(2)Line the prompts up on the left.You may want to keep the colons in a vertical column after you move the prompts.
(3)In the main program, add two more statements: Print_Entry_Screen; Print_Entry_Screen;
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 71
2.Being nice to users - ClrScr.
Pascal provides a predefined procedure to clear the screen.
Screen interaction will go smoother if unnecessary items are removed when no longer needed.
(First, remove the 2 extra Print_Entry_Screen statements.Notice that you could just load a new copy of PROG15.)
Add the following statement as the first statement in the main program:
WriteLn('This is something leftover from previous processing');
Run the program.
How does the data entry screen look now?
This problem was not apparent before, because the screen was cleared before the program executed.The message you just added makes the situation more realistic - there are often things left on the screen that need to be cleared.
The procedure, ClrScr, will clear the screen.
Where should you put ClrScr, in the main program, or in the procedure?
Right!In the procedure, because clearing the screen is really just a part of printing the entry screen.
At the beginning of the Procedure, Print_Entry_Screen, add:
ClrScr;
Run the program. Is the "leftover" message gone?
NOTE: YOU SHOULD ALWAYS CLEAR THE SCREEN AS NEEDED.EARLIER VERSIONS OF TURBO CLEARED THE SCREEN AT THE BEGINNING OF THE PROGRAM, BUT THAT IS THE TYPE OF THING YOU SHOULD NOT DEPEND ON.WHAT IF THE NEXT VERSION CHANGES?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 72
3.Getting around the screen - GotoXY.
Cursor positioning is done with the predefined procedure, GotoXY.
To find out how it works, try PROG15A.
Examine PROG15A, then run it a few times using the following values for X and Y: X Y 120 40 1 7023
Does GotoXY work the way you expected?
If that is the way you expected it to work, no problem.
If you, like me, find that X and Y seem to be reversed, you can either learn to use GotoXY as is, or write a procedure to make it work the way you want it to!
Add the following procedure before the main BEGIN END block:
PROCEDURE Locate(X, Y : Integer);
BEGIN GotoXY(Y, X);{ Note the reversed Y, X here } END;
Also change the GotoXY(X, Y) statement in the main program to:
Locate(X, Y);
Run the program several times using the values: XY 1 50 101 23 70
My own choice is to use GotoXY as is, but if you work in both Pascal and Basic at the same time, you might want some procedure like Locate, to make the cursor positioning work the same in both.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 73
4.Screen messages and accepting user input.
Examine PROCEDURE Get_First_Name in PROG15B.
Notice the use of GotoXY(13,3) to position the cursor next to the first name prompt on the screen.
Read(First_Name) is used instead of ReadLn.Read and ReadLn will be contrasted and explored in a later lesson.For now, just note that the procedure works.
Run PROG15B.
I hope you got the name right.No second chance here!
Unfortunately, mistakes are made in data entry, and you must provide a convenient way to correct them.
Look at FUNCTION OK in PROG15C.
Also notice how PROCEDURE Get_First_Name has been changed to use the information provided by FUNCTION OK.
The user can now correct typing mistakes before going on.
PROGRAMMING NOTE: OBSERVE THAT FUNCTION OK MUST BE DECLARED BEFORE PROCEDURE GET_FIRST_NAME SINCE THE PROCEDURE USES THE FUNCTION.
Run the program, entering a few wrong names of different lengths before entering the correct name (your name?)
Do you detect a problem?There are screen leftovers again!
There is another procedure, ClrEol, which clears from the cursor position to the end of the line.
Insert the statement: ClrEol;
after the GotoXY(1,23) statement in FUNCTION OK and after the GotoXY(13,3) statement in PROCEDURE Get_First_Name.
Run the program again, testing for leftovers.Enter several names of different lengths again.
How's that?You're on your way toward friendly input screens!
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 74
TURBO-LESSON 16: REAL NUMBERS
OBJECTIVES - In this lesson, you will learn about:
1.Range of Real Numbers 2.Input/Output of Real Numbers 3.Calculations with Real Numbers 4.Calculations with Integers and Real Numbers
1.Range of Real Numbers
For business processing (dollar amounts), and scientific processing, integers alone are not adequate.Decimal numbers and sometimes numbers in scientific notation are needed.
TURBO provides Real Numbers with 11 significant digits of precision in the range:
1E-38 to 1E+38
(The BCD version of TURBO provides 18 significant digits and a range of1E-63 to 1E+63, but this set of TURBO-LESSONS deals with the more limited range above.)
Run PROG16.
Enter 444.333222111 and examine the result presented in scientific notation.
How many digits are retained before the E?(I counted 11, including digits on both sides of the decimal point.)
This is the 11 significant digits of precision.Note that the last 1 you entered was dropped.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 75
2.Input/Output of Real Numbers.
You will need to know what to expect with various combinations of input and output of real numbers.
Run PROG16.
Enter 444.333222111 and study the various outputs.
When the real number, A, is output without any formatting, scientific notation is used:
4.4433322211 are the significant digits.
E+02 means multiply by 10 to the 2nd power to get the number.
If you want the number presented in some other form, you can add the :w:d formatting to the name of the variable to print.
:w Width of the print field :d Decimal positions to print
WriteLn(A:10:2);This statement would print the number, A, in a print field 10 characters wide, with 2 decimal positions.
Look at the outputs on the screen again.The formats used are printed at the left.Square brackets are printed to show the width of the field and where the numbere is printed (left or right-justified).
:-w Width of print field, left-justify the number.
Notice the use of the minus sign to force printing of the number at the left of the field.
What happens to the print field width when numbers are printed left-justified?
Run PROG16 with 3.4567 as input.
What happens when a print format is specified which will not hold all of the significant digits? Is the number rounded?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 76
3.Calculations with Real Numbers.
In PROG16 change the ReadLn(A) to ReadLn(B).
Add after ReadLn(B):
A := B + C;
The result printed will be the sum of B, which you enter, and C which is a constant, -2.0.
Run the program with 2.34 as input.
Are the results as expected?
In scientific calculations, very large, and very small numbers are sometimes needed.Can you enter these in a convenient form without a long string of zeros?
The radius of the earth is 6370000 meters. This is the same as6.37 times 100000 Which is the same as 6.37 times 10 to the 6th power Which may be entered as6.37E6 or 6.37E06 or 6.37E+6 or 6.37E+06
Run the program with 6.37E6 as input.
Try the other 3 forms listed above.
Are the results the same in all cases?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 77
Run the program with 6370000 as input.
Does it make any difference whether the number is input in scientific notation or in the usual form?
Run the program with 6.37E7 as input.
What happens when the result is too large for the format? (Count the character positions used to print A:10:2).
Get a new copy of the original PROG16.
Run the program with 6.37E-6 as input.
Notice the unformatted output is correct, but the formatted output shows nothing but zeros.
The result, A, is 0.00000637, with significant digits too far to the right to show up in the formatted output.
Change the WriteLn format, A:10:2 to A:10:6.(Notice there are two A:10:2's in the statement).
Run the program with the following values:
6.37E6,6.37E-6,6.37E-4
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 78
4.Calculations with Integers and Real Numbers.
What happens when you mix Integers and Real numbers in calculations?
Get a copy of the original PROG16 and make the following changes:
Change ReadLn(A); to ReadLn(I);
Change the prompt to Write('Enter an Integer: ');
Add after the ReadLn statement:
J := I + C;
Run the program.
What results did you get?
The "Type mismatch" refers to J.
Since the calculation involves both an integer, I, and a real number, C, the result cannot be stored in an integer variable. If the result had significant digits after the decimal, they would be lost when stored as an integer.
Change the calculation to:
A := I + C;
Run the program.
NOTE: ON YOUR OWN, YOU MAY WANT TO EXPERIMENT WITH THE WRITELN FORMATS.CHANGE THE FORMATS TO VARIOUS VALUES AND TRY THEM WITH A VARIETY OF INPUTS.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 79
TURBO-LESSON 17:A TIMING FUNCTION
OBJECTIVES - In this lesson, you will learn about:
1.Include files 2.A timing function 3.Improving timing accuracy 4.Sources of errors in timing
1.Include files.
After you have debugged and tested a subprogram, you no longer need to see the source statements anymore.It would be great if you could just use the subprogram like one of the predefined functions or procedures.
You can, almost!
Here's how:
(1)Store the subprogram in a file. You may want to use a filename extension such as .INC to mark your "Include" files.
(2)In the program where you will use the subprogram, use the special comment statement to include the file.It's form is:
{$I ABC.INC}
How it works:
As the program is compiling, the contents of the file, ABC.INC will be compiled at the point where {$I ABC.INC } occurs in the program.
Look at PROG17. Notice the statement
{$I Time.Inc Get System time in seconds}
This statement instructs the compiler to compile whatever it finds in a file named Time.Inc.
The actual function, Time, is not in PROG17.All that appears in PROG17 is the include statement.Include files provide a way to keep your programs uncluttered.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 80
Inspect Time.Inc.
For now, just note that the contents of this file are program statements that can be compiled.
Compile PROG17.Watch the bottom left of the screen.
How do you know when the include file is being compiled?
Did you see the "I"?If not, compile the program again.
2.A timing function.
The include file, Time.Inc, contains a function called Time which provides the time from the system clock.
Since this is an include file, you don't have to know how it works, just what it does.It can be viewed like a predefined function.
The function provides the system clock time converted to seconds. This makes it easy to compare two times by subtracting the earlier time from the later.
Examine PROG17 again.
PROG17 gets Start_Time from the function, Time.
A FOR loop is used to repeat something you want to time.
After the FOR loop is done, Stop_Time is obtained from Time.
The results printed give both total elapsed time and the time for a single repetition.
Run PROG17 using 1000 as the number of repetitions.
The function, Time, is itself being timed in PROG17.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 81
Run the program with the 10 as the number of repetitions.Input 10 several times and compare the output.
Run the program inputting 1 several times.
Do you think the time function is accurate?
3.Improving Timing Accuracy.
One way to improve the timing accuracy, in this case, is to average the time over many repetitions.
Run the program to complete the table below.
Number ofTime for Repetitions One Repetition 10 50 100 500 1000 2000 5000
What conclusions can you make from the results you observed?
What is the minimum number of repetitions needed for reasonably accurate results?
Run the program, inputting the "minimum" you chose above several times.Are the results accurate?
Try it again with a minimum about half as large.Are the results less accurate?
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 82
4.Sources of errors in timing.
Time to look at another problem!
What is actually being timed in PROG17?
The statement (A:=Time;)?
The timing section of PROG17 follows:
Start_Time := Time; FOR I := 1 to K DO A := Time; Stop_Time := Time;
What period of time is actually included in Elapsed_Time?
The period measured starts at the end of the execution of the statement: Start_Time := Time;
and ends at the end of the execution of the statement: Stop_Time := Time;
This includes the time needed to execute
FOR I := 1 to K DO and Stop_Time := Time;
in addition to the time for the action we want to measure:
A := Time;
Is this a serious problem?
Run the program for 1000 repetitions.
Record the total elapsed time and the time for one repetition for later comparison.
TURBO-LESSONS - A Pascal TutorialVersion 1.01Page 83
Change the FOR statement to:
FOR I := 1 to K DO; {Do nothing.Semicolon ends the FOR loop.}
Delete or comment out the statement, (A := Time;).
Run the program for 1000 repetitions.
Record the total elapsed time and the time for one repetition.
These are times with the (A := Time;) statement removed.
How do these times compare to the times recorded in the previous exercise?
Are these times at least 10 times as small as the times in the previous exercise?
Do you think you are getting a reasonable measure of the Time function?
Change the FOR statement back to its original form:
FOR I := 1 to K DO
After the FOR statement, add the statement:
J := 2;
Run the program for 1000 repetitions.
Record the results. How do they compare with the times for the FOR loop?
Do you know how much time is needed to execute (J := 2;)?
Try to formulate a rule to help you decide whether you are getting reasonable results in a particular case using the Time function.