TURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 1 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 Tutorial Version 1.01 Page 2 T A B L E O F C O N T E N T S Page 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 Œ TURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 3 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. 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. **************************************** D I S T R I B U T I O N N O T I C E **************************************** TURBO-LESSONS are being distributed as USER-SUPPORTED software. 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 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, 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. 2. Club members are informed that TURBO-LESSONS are distributed as user-supported software. 3. TURBO-LESSONS are distributed unmodified. Œ TURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 4 TURBO-LESSON 1: GETTING STARTED OBJECTIVES - In this lesson you will learn about: 1. Loading TURBO 2. Using the Main Menu to Load, Compile, and Run a program INTRODUCTION 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 Tutorial Version 1.01 Page 5 1. Loading TURBO. To get started, put a diskette with TURBO PASCAL in your default drive. ##### DO: 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 7 ******************** Run This option is used to execute a program, compiling it first, if necessary. ##### DO: 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 8 ##### DO: 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: Type O. The compiler Options menu is displayed. You can choose the various compiler options by typing the corresponding letter. ##### DO: 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, ##### DO: 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. ŒTURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 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. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: Type ctrl-k, d. Computer responds: Main menu. 3. - 6. Objectives 3 to 6 are covered in PROG2. To begin, ##### DO: 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: ##### DO: 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-LESSONS - A Pascal Tutorial Version 1.01 Page 12 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. ##### DO: 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 Tutorial Version 1.01 Page 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 declaration may 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 14 ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 15 ##### DO: 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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 Tutorial Version 1.01 Page 17 ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: Compile and run PROG4. When prompted, type 12 and enter. Run it again and enter -34. ##### DO: 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 Tutorial Version 1.01 Page 19 ##### DO: 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.) ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: Use the editor to enter the following short program (omit the comments, if you like): PROGRAM ABC; VAR A, 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 Tutorial Version 1.01 Page 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. ##### DO: 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); ##### DO: 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? ##### DO: 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 Tutorial Version 1.01 Page 22 The division operators, div and mod are not used in PROG5. To see how they work, ##### DO: 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? ##### DO: 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. ##### DO: 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. ##### DO: Before going on, try adding a few WriteLn statements to the program to improve the readability of the output. Œ TURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 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. ##### DO: 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: ##### DO: 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! ##### DO: 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 Tutorial Version 1.01 Page 24 ##### DO: 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 Tutorial Version 1.01 Page 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 Tutorial Version 1.01 Page 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 < 10 TRUE I < 10 TRUE, 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). ##### DO: 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. ##### DO: 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 ">". ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: 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. ##### DO: Run the program several times, experimenting with various input values. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: Examine PROG7. A variable named Response, of type CHAR, is used to store the character entered in response to a multiple choice question. ##### DO: Run the program several times, entering wrong responses, and the correct response, D. Also try lower case d. ##### DO: 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 either or both of the simple conditions are true. The correct response, D, is checked in both upper and lower case to make responding easier. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: 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 . . . ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: 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.) ##### DO: 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 Tutorial Version 1.01 Page 31 ##### DO: 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 Tutorial Version 1.01 Page 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 Tutorial Version 1.01 Page 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. ##### DO: 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 34 ##### DO: 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, IF for 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 Tutorial Version 1.01 Page 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). ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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. ##### DO: 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? ##### DO: Run the program several times using the following values for I: 123, 1234, -1234, 12345 Œ TURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 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; ##### DO: Run PROG9 several times to see how it works. Experiment with both positive and negative numbers. What happens if High is smaller than Low? ##### DO: 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? ##### DO: 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? ##### DO: 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? ##### DO: Change the FOR statement to: FOR Index := Low + 1 TO High DO Run the Program. ŒTURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 38 TURBO-LESSON 10: WHILE STATEMENT OBJECTIVES - In lesson 10 you will learn about: 1. CONSTant declaration 2. WHILE statement 3. Delay timing loop 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: CONST Constant_Name_1 = Value_1; Constant_Name_2 = Value_2; . . . Constant_Name_n = Value_n; Some examples: CONST PI = 3.14159; Fahr_Freeze = 32; Cels_Freeze = 0; Message_1 = 'This is a string constant'; ##### DO: Run PROG10 a time or two to see what it does. ##### DO: Edit the constant declaration, Wobble_Size = 5; to Wobble_Size = 10; Run the program. What effect did you see from the change? Œ TURBO-LESSONS - A Pascal Tutorial Version 1.01 Page 39 ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 40 ##### DO: 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. ##### DO: 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. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 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'. ##### DO: 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. ##### DO: 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 Tutorial Version 1.01 Page 42 ##### DO: Change the delay in the loop from 500 to 2000 and run the program. ##### DO: 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: ##### DO: 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!