The Pascal programming language was developed during the early days of microcomputing to meet the programmers demand for a more powerful language than BASIC. Whereas BASIC is a good language for beginners, Pascal is an excellent general-purpose language for business and engineering. Pascal's strength lies in its highly structured language elements.
This chapter (Overview of Pascal) gives you an overview of Pascal, offering a history of the language and a description of its fundamental commands - including the major similarities and differences between Pascal and BASIC. Today, BASIC has become a fairly powerful language with features that imitate some of Pascal's. That is a tribute to Pascal, one of the first programming language designed from the start as a well-structured programming language. Pascal offers significant speed improvements over BASIC because it always runs in a complied environment.
In the early 1970s, a man named Niklaus Wirth saw the need for teaching structured programming techniques. Structured programming is the process of writing orderly programs without excessive, unnecessary branching. Structured programs are easy to maintain - an important consideration, because today's data processing departments must change their computer software systems to meet the changing demands of the world. Niklaus Wirth noticed that his students did not adapt well to structured programming techniques. He blamed the languages of the day, not the students. Mr. Wirth set out to design his own programming language that strongly supported structured programming - a language that included control constructs and made it difficult not to write structured programs. Mr. Wirth named his language Pascal after the 17th century mathematician Blaise Pascal. (Pascal was one of the first programming languages whose name was not an acronym for something else.)
Mr. Wirth designed the language as a tool for teaching proper programming methods, he was as surprised as anyone that Pascal became an enormously successful general - purpose programming language.
Pascal became one of the most widely used programming languages for microcomputers - second only to BASIC - during the late 1970s and 1980s. Although there were other languages that offered similar structured commands such as Algol, none of the other programming languages was small enough to fit in the limited memory space of the early microcomputers.
Pascal enjoyed an overwhelming success. Entire programming magazines were devoted to the language, and programming departments all over the world started using Pascal exclusively. Pascal became a requirement in college curriculums - right after BASIC - so that new programmers could learn as early as possible to program the "right way."
During the 1980s, it appeared the entire world would convert almost exclusively to Pascal. There had been many programming languages created before Pascal, and many were thought to be the answer to various programming needs. However, no language before Pascal created such a furor in the programming community; Pascal generated a devoted following never before seen for a programming language. As Pascal began the language choice of business that had stayed with COBOL and FORTRAN throughout the previous language "fads."
Perhaps as a result of the times, Pascal's huge popularity dwindled almost faster than it grew. Although Pascal still enjoys a large following, and Pascal compilers continue to sell well, Pascal has ended up where it began - in the classroom. Today, Pascal is taught to new programming because it uses the "proper" programming techniques that a good programming should possess. Nevertheless, Pascal is no longer taught for its own sake. Pascal is viewed as a language that teaches the proper fundamentals that a programmer needs before moving on to another language - most commonly C.
Pascal's use in data processing departments is limited these days. C has taken the world by storm since the late 1980s and continues to do so.
Given its decline in use, should you spend time learning Pascal? Of course. Pascal is still the cornerstone of proper programming techniques, easier to learn than C, and the skills you learn with the Pascal language stay with you no matter which language becomes your primary programming language.
Listing 1.1 shows you the structure of a simple Pascal program. Do not be concerned with understanding everything - or anything - in this program just yet. Simply skim through it to get a feel for the way Pascal programs look. Pascal's key features and programming statements are described throughout the next few sections.
---------------------------------------------------------------------------------------------------
Listing 1.1 - A simple Pascal program. ---------------------------------------------------------------------------------------------------
PROGRAM ShowName;
USES Crt;
VAR
Row, Col : INTEGER;
FirstName : STRING[10];
BEGIN
CLRSCR;
WRITE('What is your first name? '); {Get name to display}
READLN(FirstName);
{Show the name randomly on the screen}
GOTOXY(10,15);
WRITE(FirstName);
GOTOXY(50,20);
WRITE(FirstName);
GOTOXY(1,1);
WRITE(FirstName);
GOTOXY(70,5);
WRITE(FirstName);
GOTOXY(60,10);
WRITE(FirstName);
{Show name in columns}
For Row := 1 to 24 DO
BEGIN
GOTOXY(1,Row);
FOR Col := 1 to 5 DO WRITE(FirstName : 10);
END; {for}
{Show message in the middle of the screen}
GOTOXY(30,12);
WRITE('That''s all, ',FirstName);
READLN; {Wait for an ENTER keypress}
END. {ShowName}
Pascal is a rich programming language with lots of power. Its many control structures give you a wide assortment of commands form which to choose. The following sections explain the key language elements of Pascal and guide you through an overview of the language. Once you finish this chapter, you will have a good idea of what Pascal programs look like and you will be able to read and understand simple Pascal programs.
All Pascal programs begin with the keyword PROGRAM. As with any Pascal commands, PROGRAM may be in uppercase or lowercase letters - but most Pascal programmers out commands in uppercase to distinguish them from variables names. After PROGRAM, you must specify a name for your program. The name is not the filename - it is just a name from 1 to 63 characters, beginning with any letter of the alphabet, which refers to the program that follows. The PROGRAM line should look similar to this
PROGRAM ProgramName;
ProgramName does not have to be the actual filename; however, many programmers use the actual filename for easier documentation.
The PROGRAM statement line must end with a semicolon. Unlike BASIC, all statements in Pascal - with one minor exception explained later in this section - must end in a semicolon. The semicolon tells Pascal that the statement has ended and it can move on to the next statement. For beginning Pascal programmers, the semicolon is one of the easiest things to forget when writing a Pascal program. If you forget a semicolon at the end of a command. Pascal reminds you with an error when you compile the program.
Somewhere near the top of every Pascal program is a BEGIN statement. The actual body of the program begins with BEGIN.
All Pascal programs end with the END keyword followed by a period. The last, END, is the only exception to the rule that all Pascal statement end in a semicolon. Unlike BASIC's optional END statement, Pascal requires END. Therefore, here is a skeleton of a Pascal program with the proper starting and ending lines.
PROGRAM CalWages;
BEGIN
{All the Pascal Statements to be type here}
END.
Semicolons always end executable statements. Statements such as IF-THEN, FOR, and REPEAT lines, however, do not end with a semicolon; they begin the statement but are not, themselves, complete statements.
There is always a matching END for every BEGIN. As you will learn later in this chapter, there can be more than one pair of BEGIN-END statements. A block is one or more statements between each pair of EBGIN-END statements.
Pascal comments - the lines of documentation you put into your programs to make the code more understandable to other people - reside between two curly braces. Unlike comment statements in BASIC, requiring REM on every line that is a remark, Pascal's comments can span many lines in the program. The comment begins with a left brace and ends with a right brace - even if that right brace appears many lines later.
There is another kind of Pascal comment that is rarely used today. It begins with (* and ends with *). Pascal treats all text between (* and *) as a comment. The following two examples are valid comments:
{ Calculate net pay }
and
(* Calculate net pay *)
Listing 1.2 is a small program with comments scattered throughout. The first three lines contain a multi-line comment. A single-line comment appears on a line by itself before the WRITELN() statements. A few comments are scattered to the right of some later statements as well.
-------------------------------------------------------------------------------------------------
Listing 1.2 - A program demonstrating the use of comments. -------------------------------------------------------------------------------------------------
{ This program puts a few values in variables
and then displays those values to the screen.
These three lines are comments }
PROGRAM DemoComments1;
USES CRT;
VAR
Age : INTEGER;
Salary : REAL;
BEGIN
CLRSCR;
Age : = 32; {Stores the age}
Salary := 25000; {Yearly salary}
{Display the results on the screen}
WRITELN( Age );
WRITELN( Salary );
END. {DemoComments1}
-------------------------------------------------------------------------------------------------
As shown in the preceding program, Pascal programmers often put the name of the program ( first seen after the PROGRAM statement ) in a comment directly following the final END. This signals to anyone reading the program that the entire program has come to an end (of course, so does the period after END).
Use ample comments throughout your Pascal programs to increase their readability and maintainability.
Pascal's variable and data types are similar to those used in BASIC. Because you, the Pascal programmer, are responsible for the variables your programs need, you should learn the naming rules for variables. Here are the variable naming rules for most versions of Pascal:
All variable names must be between 1 to 63 characters in length.
All variable names must begin with a letter of the alphabet or the underscore character (_).
All characters following the first character can be any mixture of letters, numbers, and underscores.
The following are all valid variable names:
SALES
Payroll93
_AcctRec
Volume_DECEM
These, however, are not valid variable names:
93Payroll
Variable names cannot begin with a number
Total Amount
Variable names cannot contain a space
Dept$@#$MKtg
Variable names cannot contain special characters
As with BASIC, Pascal does not distinguish between uppercase and lowercase variable names. Therefore, the following four examples represent the same variable in Pascal :
Sales
sALES
SALES
sales
Pascal variables can hold different types of data. The data can be either numeric or character. Table 1.1 describes the types of data that variables can hold and gives an explanation of each type. Pascal supports many more data types than BASIC.
Table 1.1 - Pascal data types.
Type | Examples | Description |
CHAR | 'A', '*' | Single characters. |
STRING | 'Harry' | String of zero or more characters. |
SHORTINT | -19, 0, 88 | Whole numbers, without decimal points, from -128 to 127. |
BYTE | 1, 255 | Whole positive numbers, without decimal points, from 0 to 255 |
INTEGER | 45, -179 | Whole numbers, without decimal points, from -32768 to 32767. |
LONGINT | 456787 | Extremely large or extremely small whole numbers. |
WORD | 7, 60000 | Whole positive numbers, without decimal points, from 0 to 65535. |
REAL | 0.01 | Real numbers, with decimal points, from -2.9E-39 to 1.7E+38. |
SINGLE | 956.534 | Real numbers, with decimal points, from -1.5E-45 to 3.4E+38. |
DOUBLE | 83544972.8 | Real numbers, with decimal points, from -5.0E-324 to 1.7E+308. |
EXTENDED | 7628295237.212 | Real numbers, with decimal points, from -3.4E-4932 to 1.1E+4932. |
Unlike BASIC, Pascal requires that you explicitly define all variables before you use them. To define a variable in Pascal means to list - at the top of every program - each variable name and its corresponding type. You must define each variable to the program before the body of the program can do anything with that variable.
The first column in Table 1.1 shows the names you must use when you define variables in Pascal. Notice that the name of each data type is in uppercase, which is the preferred, but not required, method in Pascal.
To define one or more variables at the top of a Pascal program, begin the line with the VAR command. VAR informs Pascal that a variable definition is about to follow. You only have to list your variable names and their respective data types following the VAR statement. The following is a variable declaration section of a Pascal program :
VAR Age : SHORTINT;
Salary : REAL;
Dependents : BYTE;
After Pascal compiles the three lines, it recognizes three variables named Age, Salary and Dependents to be used later in the program. Because Pascal is a freeform language, the extra spaces in the variable definition code are optional. Pascal would understand the code if it looked like this:
VAR Age : SHORTINT; Salary : REAL; Dependents : BYTE;
Obviously, the first method - with spacing - is more readable. The more examples you see, and the more you program in Pascal, the quicker you establish good spacing technique in your Pascal program.
When you define a string variable in Pascal, you must think ahead more than you have to in BASIC. To write an efficient program, you must tell Pascal - at variable definition time - the longest string value you will ever store in a string variable. In other words, of you want to define a variable to hold your company's name, you must count the number of characters in the company name and provide this information to Pascal at the time you define the variable. If your company name is 14 characters long, the following statement could be used to define a string variable to hold the name :
VAR CompName : STRING[14]; {No name longer than 14 will fit}
Actually, you can leave off the string's maximum length in brackets, but if you do, Pascal reserves 255 characters of storage for the string. If your string is much shorter than 255 characters, this can waste a lot of extra memory space.
Similar to BASIC, Pascal uses an assignment operator to store values in variables, with one exception - Pascal uses a two-character operator (:=) for assignment. Pascal reserves the equal sign for testing within relational operations (BASIC used = for both assignment and testing). Here are some examples of assigning values to variables to Pascal :
Age := 32;
MyName := 'Sally';
Put single quotation marks around any data you assign to a string variable - unless you are assigning it the value of another string variable. In the following line, for example, you should not put single quotation marks around MyName because it is the name of another string variable :
OurName := MyName; {Assign one string variable to another}
Pascal uses math symbols that are similar to those used in BASIC. Pascal's operator hierarchy is also similar to BASIC's. Table 1.2 shows the regular Pascal math operators and their precedence.
Table 1.2 - Pascal's primary math operators.
Precedence | Operator | Example | Description |
1 | (, ) | (3+2)/2 | Overrides all other precedence. |
2 | *, /, DIV | 8 DIV 2 | Multiply, real divide, and integer divide. |
3 | +, - | 2+3-2 | Addition and subtraction. |
When you divide an integer variable or an integer constant by another integer, you must use the DIV operator. Although DIV looks more like a command than an operator, Pascal performs integer division when it sees DIV. When you use DIV, the result Pascal returns is always an integer (whole number). For example, the following statement stores a 6 in the integer variable Result because 4 goes into 25 six times.
Result := 25 DIV 4;
If you define Result as a REAL variable and use the real number division operator(/), the following statement would store 6.25 in Result.
Result := 25 / 4;
The WRITE and WRITELN functions are Pascal's primary methods of writing data to the screen. These are not Pascal commands. Pascal does not include any commands that perform input or output (neither do C and C++). WRITE and WRITELN are functions, or built-in-routines - supplied by the makers of your Pascal compiler - that perform output. The distinction between command and functions is trivial for beginners of the language.
WRITELN sends data to the screen in a manner similar to PRINT in BASIC. WRITE also sends data to the screen, but does not perform an automatic carriage return; that is, the cursor stays on the same line. Look at the following two examples,
WRITELN ('I am learning Pascal.');
WRITELN ('Pascal is a well-structured language.');
which displays this on the screen:
I am learning Pascal.
Pascal is a well-structured language.
WRITE is not as generous. These three lines,
WRITE('One');
WRITE('Two');
WRITE('Three');
produce on the screen the following single line;
OneTwoThree
Therefore, if you are calculating results and printing them as you calculate, you can use a combination of WRITE and WRITELN. WRITE will display the values across one line as you calculate and print them. Then, display the last value with WRITELN so that the cursor moves down to the succeeding line for the next group of output statements.
The program in Listing 1.3 uses a combination of WRITE and WRITELN statements to print the values of some data.
----------------------------------------------------------------------------------------------------
Listing 1.3 - A program that assigns values to variables and prints them on the screen. ----------------------------------------------------------------------------------------------------
{ This program puts a few values in variables and then displays those values and labels to the screen.}
PROGRAM DemoStringConstants;
VAR
Age : INTEGER;
Salary : REAL;
Dependents : BYTE;
BEGIN
Age := 32; {Stores the age}
Salary := 25000.50; {Yearly salary}
Dependents := 2; {Number of dependents}
{Display the results}
WRITE (' Age: ');
WRITELN (Age);
WRITE('Salary: ');
WRITE(Salary);
WRITE('Dependents: ');
WRITELN(Dependents);
END. {DemoStringConstants}
----------------------------------------------------------------------------------------------------
The preceding program produces the following output:
Age: 32
Salary: 25000.500001
Dependents: 2
As is obvious from this example, something odd happens when you print REAL data in Pascal. Pascal does not realize that you want only two decimal places. Because Pascal internally stores REAL data (along with all the other real data types such as SINGLE and DOUBLE) to several decimal places, it prints those extra decimal places. Sometimes, as happened here, a slight fractional error creeps in as well. You can limit the number of decimal places printed by the following the variable with a width and decimal specifier as in the following statement:
WRITELN(Salary:8:2);
The :8:2 tells Pascal to print the Salary variable within eight spaces, reserving two of those eight spaces for the fractional part of the number. If this WRITELN statement had been included in the preceding program, the following results would have been displayed on the screen.
Age: 32
Salary: 25000:50
Dependents: 2
You must do some extra work if you want to print values to your printer instead to your screen. Anytime you want to output data to your printer, you must include the following statement after the PROGRAM line in your program:
USES printer;
When Pascal compiles this line, it loads some extra code it needs to output to your printer. Additionally, at the beginning of each WRITE and WRITELN statement in your program, you must include the LST device name. LST instructs Pascal to write to the printer and not to the screen when you request WRITE or WRITELN. The program in Listing 1.4 outputs the data to the printer instead of to the screen.
----------------------------------------------------------------------------------------------------
Listing 1.4 - This program prints the variable values to a printer. ----------------------------------------------------------------------------------------------------
{ This program puts a few values in variables and then displays those values and labels to the printer.}
PROGRAM DemoStringConstants;
USES printer; {sets up the printer}
VAR
Age : INTEGER;
Salary : REAL;
Dependents : BYTE;
BEGIN
Age := 32; {Stores the age}
Salary := 25000.50; {Yearly salary}
Dependents := 2; {Number of dependents}
{Print the results}
WRITE (LST, ' Age: ');
WRITELN (LST, Age);
WRITE(LST, 'Salary: ');
WRITE(LST, Salary);
WRITE(LST, 'Dependents: ');
WRITELN(LST, Dependents);
END. {DemoStringConstants}
Pascal offers a READLN function that gets input from the keyboard and is similar to BASIC's INPUT command. Unlike INPUT, READLN does not display a question mark when it executes; if you want a question mark to appear as a prompt, you must supply your own.
The following statement waits for the user to type a number, and then stores that number in the Sales variable before proceeding to the rest of the program:
READLN(Sales);
The following statement reads three values from the keyboard:
READLN(Num1, Num2, Num3);
With a multiple-input READLN, the user must separate each input number with a space. Be sure to tell the user exactly what she or he must type at the keyboard. The program in Listing 1.5 prompts each segment of input with an appropriate message.
----------------------------------------------------------------------------------------------------
Listing 1.5 - A Pascal program that prompts the user for input.
----------------------------------------------------------------------------------------------------
{User inputs 3 values using READLN
The Values then print to the printer. }
PROGRAM NameEmp;
USES Printer;
Var
Name : STRING[25];
Years : INTEGER;
Balance : REAL;
BEGIN
WRITE('What is your name? ');
READLN(Name);
WRITE('How many years have you worked here? ');
READLN(Years);
WRITE('What is your investment plan balance? ');
READLN(Balance);
WRITELN(LST, 'You typed the following: ');
WRITELN(LST, 'Name: ',Name);
WRITELN(LST, 'Years: ',Years);
WRITELN(LST, 'Balance: ',Balance);
END. {NameEmp}
When comparing data, Pascal uses the same relational operators as BASIC. Unlike BASIC, however, Pascal's equal sign is used solely for equality testing - not for assignment. Pascal has an IF-THEN command, similar to BASIC's. The format of PASCAL's IF-THEN is
IF condition THEN
BEGIN
{One or more Pascal Statements go here}
END;
The IF-THEN command is used to make a decision. If the condition is true, every statement between BEGIN and END executes. If the condition is not true, none of the statements between BEGIN and END execute. Whatever the condition, the rest of the program following END continues execution when IF finishes.
If you only want to perform one statement if the condition is true, you do not need to specific BEGIN and END. For example, here is a valid Pascal IF-THEN statement:
IF (Bonus >= 5000) THEN WRITELN('You did well!');
This is the same statement with a BEGIN-END block:
IF (Bonus >= 5000) THEN
BEGIN
WRITELN('You did well!')
END;
This IF says that if Bonus is greater than or equal to 5000, display a message on the screen that says 'You Did Well!'.
Pascal also includes an ELSE option for the IF-THEN command. The format of the IF-THEN-ELSE is
IF condition THEN
BEGIN
{One or more Pascal statements go here}
END
ELSE
BEGIN
{One or more Pascal statements go here}
END;
As with the simple IF, when the body of the ELSE is only one line, you do not have to use the BEGIN-END keywords.
The program in Listing 1.6 demonstrates the IF-THEN-ELSE control statements.
-----------------------------------------------------------------------------------------------------
Listing 1.6 - A program that demonstrates the IF-THEN-ELSE comparison.
-----------------------------------------------------------------------------------------------------
{Improved program to display a message depending on years of service using the IF-THEN-ELSE}
PROGRAM Service2;
VAR Yrs : INTEGER;
BEGIN
WRITE('How many years of service? ');
READLN(Yrs);
IF (Yrs >20) THEN
BEGIN
WRITELN('Give a gold watch');
END
ELSE IF ((Yrs > 10) and (Yrs <= 20) ) THEN
BEGIN
WRITELN('Give a paperweight');
END
ELSE WRITELN('Give a pat on the back');
END. {Service2}
----------------------------------------------------------------------------------------------------
Try to follow the program's logic. It uses an IF-THEN-ELSE within a simple IF statement. The program displays an appropriate company reward based on the employee's years of service. The IF lets the program work differently for different employees. Here is a sample output from the program:
How many years of service? 5
Give a pat on the back
The program makes a different decision if the number of years of service is greater, as the following output shows:
How many years of service? 16
Give a paperweight
Pascal has both a FOR loop and a WHILE loop that correspond to those in BASIC. Pascal also offers another loop construct called the REPEAT loop. Depending on your program, the REPEAT might be easier to use than the while. This section shows you how to loop in Pascal.
Here is the format of Pascal's FOR loop:
FOR index := start TO last DO
BEGIN
{One or more Pascal statement go here}
END;
The FOR loop always counts up. The loop begins by assigning to the index variable the value of start. The loop continues - with index incrementing by 1 each iteration of the loop - until the index variable becomes equal to last. This is exactly the same as BASIC's FOR loop, with the exception that Pascal does not allow for an increment other than 1.
Here is a simple program that prints a message five times based on the FOR loop's execution.
{Program that changes the FOR loop control printing}
PROGRAM control1;
VAR i : INTEGER;
BEGIN
FOR i := 1 TO 5 DO
BEGIN
WRITELN('*** Computers are fun! ***);
END;
END. {Control1}
If you want a FOR loop to count down, you must use a different form of FOR. The following is the format of a FOR loop that decrements the index variable:
FOR index := start DOWNTO last DO
BEGIN
{One or more Pascal statement go here}
END;
With DOWNTO, you must ensure that the start value is greater than last so that Pascal can decrement index between the two values. To illustrate the countdown FOR loop, the following program counts down from 10 to 1 and prints *** Blast off! ***.
{Program that counts down using a FOR loop}
PROGRAM Control1;
VAR i : INTEGER;
BEGIN
FOR i := 10 DOWNTO 1 DO
BEGIN
WRITELN(i);
END;
WRITELN('*** Blast off! ***');
END. {Control1}
Pascal's WHILE loop is similar to BASIC's WHILE loop. The Pascal WHILE loop continues looping while a relational condition is true. As soon as the relational condition is false, the WHILE loop ends and the rest of the program continues. Here is the format of WHILE:
WHILE condition DO
BEGIN
{One or more Pascal statement go here}
END;
The following program demonstrates the WHILE loop and is a routine that could be used inside a larger program. This routine tests an age entered by the user to ensure that the age fills between two values. This is known as validity checking. When you ask the user for input, you usually check to see whether the input is valid by making sure it fails in a range between two reasonable values. For examples, if the user typed 997 as an age, the number would be wrong because no one lives that long.
{Program that helps ensure that age values are reasonable}
PROGRAM Age1;
VAR Age : INTEGER {Age typed by user}
BEGIN
WRITE('What is the age of the student? ');
READLN(Age);
WHILE ((Age < 14) OR (Age > 100)) DO
BEGIN
WRITELN(' *** The age must be between 14 and 100 *** ');
WRITELN('Try again...');
WRITELN;
WRITE(What is the student''s age? ');
READLN(Age);
END;
WRITELN('You typed a valid age.');
END. {Age1}
Here is the output from the preceding program. Notice that the WHILE loop keeps an incorrect age from being entered.
What is the age of the student? 217
*** The age must be between 14 and 100 ***
Try again...
What is the student's age? 21
You typed a valid age.
Pascal offers one additional loop control statement called the REPEAT statement. You can use REPEAT when the logic of the WHILE loop doesn't quite work out. Whereas WHILE continues looping as long as the relational condition is True, REPEAT continues looping as long as the relational condition is False. Here is the format of REPEAT:
REPEAT
{One or more Pascal statements go here}
UNTIL condition is true;
REPEAT is slightly easier to program than WHILE because you don't have to worry with BEGIN-END blocks. Depending on your program's logic, REPEAT might be a better choice than either FOR or WHILE. The program in Listing 1.7 uses a REPEAT loop to get a number from the user. The program keeps repeating - and obtaining numbers - until the user types a 0.
----------------------------------------------------------------------------------------------------
Listing 1.7 - A program that uses a REPEAT loop.
----------------------------------------------------------------------------------------------------
{A program that accepts a list of numbers and shows the total and average.}
PROGRAM Adder;
VAR
Total : INTEGER; {running total}
Count : INTEGER; {# of number typed by the user}
Num : INTEGER; {number typed by user}
BEGIN
Total := 0;
Count := 0;
REPEAT
WRITE('What is your number (0 will end the input)? ');
READLN(Num);
Total := Total + Num;
IF Num <> 0 THEN Count := Count + 1;
UNTIL (Num = 0);
WRITELN;
WRITELN(' The total is ';Total);
WRITELN('The average is ', (Total/Count):2:1);
END. {Adder}
This program's logic is one of the most advanced in this chapter, and yet, it still is not too difficult to follow. The program first assigns both a Total and a Count variable to zero. As the user types numbers into the program in response to the READLN, the numbers are added to the total and the counter is incremented by 1. Because the program prints an average of the numbers, it must keep track of the total of the values as well as the number of values entered. The loop continues, thanks to the REPEAT; until the user types a 0 to end the input. A FOR loop would not work in this program because you don't know how many values the user wants to average. A WHILE would not work either because you want the program to loop as long as the number is not zero (as long as the condition is False).
Language Spotlight
It is extremely common for you to add or subtract 1 from variables. The Adder program in Listing 1.7 used a counter variable to count the number of entries made by the user. To count, the program added 1 to a count variable with the following statement:
count := count + 1;
You can also subtract one from a variable in the same way:
count := count - 1;
Because adding and subtracting 1 is so common, the designers of Pascal included two built-in functions that make adding and subtracting 1 from variables easy. To add 1 to count, you could simply do this:
INC(count); {Adds one to count.}
INC means increment. To subtract 1 or decrement 1 from variable, you can do this:
DEC(count); {Subtract one from count.)
If you want to add or subtract more than one, you can do so with INC and DEC. The following statement adds 24 to the variable named MyNumberOfDays:
INC(MyNumberOfDays,24);
The second value, if you choose to include one, is the value Pascal adds or subtracts to or from the first variable. Using INC in this case is easier than having to write out the entire assignment expression, such as
MyNumberOfDays := MyNumberOfDays + 24;
Program can be quite long. When a program gets too big, it often gets complex. To tackle the complexity, break the program into small section and execute those parts. You then can ease the programming burden for longer programs. In Pascal, one small section is called a procedure. Actually, you have seen procedures throughout this chapter. The entire Pascal program between the opening BEGIN and the final END statements is the program's main procedure. In other words, the entire program is one long, unnamed procedure. If you want to include several other procedures, you must name them with the PROCEDURE statement. Here is the format of the PROCEDURE statement:
PROCEDURE ProcName;
The ProcName can be any name that follows the same naming rules you saw earlier for variables. The following is a simple procedure definition from a program; it writes a name and address to the printer.
PROCEDURE NameAddr;
USES printer;
BEGIN
WRITELN(LST,'Elaine Harris');
WRITELN(LST,'304 W. Sycamore');
WRITELN(LST,'Burnamk, CA 92332');
END;
This procedure might be part of a larger program that contains many procedures. Once you type this procedure into a program, you need some way to execute it.
All procedures must be placed before the main procedure. In other words, if you added procedures to any of the programs from this chapter, you would add the procedures before the existing BEGIN statement.
To execute a procedure in Pascal, you only have to call it by name. Pascal programs contain procedures are much easier to read than BASIC programs with lists of GOSUB statements. If you assign descriptive names to yours procedures, you can then write statements such as the following
GetHours;
CalcPay;
PrintCheck;
If these three lines made up the main procedure of a Pascal program, you would be able to understand the program without even knowing Pascal! Some well-written segments of Pascal programs read just like statement written in English. This program contains the three procedures GetHours, CalcPay and PrintCheck. Without knowing Pascal, you can assume that these three procedures ask the user for some payroll data, calculate the given payroll amounts and finally print the checks.
Listing 1.8 is the payroll program. The program uses readable procedure calls and reviews some of the Pascal commands you learned throughout this chapter.
----------------------------------------------------------------------------------------------------
Listing 1.8 - The Pascal payroll program using procedures.
----------------------------------------------------------------------------------------------------
{Payroll program that uses procedures to separate sections into manageable subroutines}
PROGRAM Payroll;
USES printer;
VAR
Ans : STRING[1];
Fullname : STRING[25];
Rate : INTEGER;
TaxRate : REAL;
GrossPay : REAL;
Taxes : REAL;
NetPay : REAL;
PROCEDURE AskUser; {Ask if user wants to see calculations and check}
BEGIN
WRITELN('Do you want to see your payroll and print a check (Y/N) ');
READLN(Ans);
IF ((Ans = 'N') or (Ans = 'n')) THEN HALT; {Quit program if responds with N.}
END;
PROCEDURE GetHours; {Data gathering Section}
BEGIN
WRITELN('What is your name? ');
READLN(Fullname);
WRITELN('How many hours did you work? ');
READLN(Hours);
WRITELN('How much do you make per hour? ');
READLN(Rate);
END;
PROCEDURE CalcPay; {Calculation section}
BEGIN
TaxRate := 0.35;
Grosspay := Hours * Rate;
Taxes := Taxrate * GrossPay;
NetPay := GrossPay - Taxes;
END;
PROCEDURE DispPay; {Screen display of data}
BEGIN
WRITELN; {Prints a blank line}
WRITELN('Here is your payroll information:');
WRITELN('Name: ', Fullname);
WRITELN('Gross pay: $', GrossPay:8:2);
WRITELN('Taxes: $', Taxes:8:2);
WRITELN('Net pay: $', NetPay:8:2);
END;
PROCEDURE PrintCheck; {Print the paycheck}
BEGIN
WRITELN(LST, 'Pay to the order of ', Fullname);
WRITELN(LST);
WRITELN(LST,'The amount of: ***********$',NetPay:8:2);
WRITELN(LST, 'Benson Corp.');
WRITELN(LST, '1212 E. Oak');
WRITELN(LST, 'Miami, FL 21233');
WRITELN;
WRITELN(LST,'___________________________');
WRITELN(LST,' (Jim Gaines, Treasurer) ');
END;
{Main procedure follows}
BEGIN
WRITELN('** Payroll Program **'); {Title}
Askuser;
GetHours;
CalcPay;
DispPay;
PrintCheck;
END. {Payroll}
When a Pascal program contains multiple procedures, keep in mind that the main procedure appears last. The first statement that actually executes in this program is the WRITELN statement in the last (main) procedure.
As you can see, a Pascal program is not always shorter than its equivalent BASIC program. After the Pascal compiler finishes compiling, however, the resulting Pascal program generally is smaller than a BASIC program - and usually runs faster. In other words, a shorter program listing does not always mean a better program. Although the Pascal code might be longer, the procedure names that Pascal requires make the program much easier to follow than similar BASIC code which uses a web of cryptic line numbers.
The only statement in this program that you have not yet been introduced to is the HALT statement in the AskUser procedure. If the user types an N in response to the question, the HALT statement forced the program to end and returns the user to the operating system.
You now have a preliminary understanding of the Pascal programming language and how it compares to BASIC. Pascal's readable procedure names, rich assortment of data types, and abundant control statements - such as WHILE, FOR and REPEAT - made it one of the first truly structured, easy to maintain programming languages written for microcomputers.
Although compiled programs take longer to prepare than interpreted ones such as BASIC programs), the compiled programs run faster. Businesses prefer compiled programs because runtime speed is important. Most of today's Pascal compiled compile at tremendous speed. For shorter program, you notice very little difference in the compilation times of Pascal programs and the startup times of interpreted code. Consequently, Pascal is a good language to use when optimization of both compilation time and runtime is important.
Despite its richness as a structured programming language, Pascal has been chosen as the preferred language among microcomputer programmers. Today, the C programming language - although often not as easy to read and understand - has gained a much wider acceptance among programmers. Nevertheless, most people find that first learning Pascal makes learning C easier.