What can I use to learn Pascal

I found this course, which I took around 1990, in my records. I shortened it and translated it into HTML. It does not cover the entire language range of PASCAL.

A PASCAL compiler can be found as a package under Linux fp-compiler in the repositories. The compiler starts with the command fpc called.

PASCAL is the language of the Delphi development environment. The successor to Delphi is the Lazarus project, which comes with the lazarus is available as a package in the Linux repositories.

As part of a PASCAL program

A PASCAL program is written with a type of word processor and then translated by the compiler. A minimal PASCAL program looks like this:

PROGRAM program name; BEGIN END.

The first line tells the compiler that the following is not a letter or the like, but a program. It consists of the defined word PROGRAM, followed by a freely selectable program name. It just has to meet the PASCAL requirements for a name. A name in PASCAL can only consist of letters and numbers and the underscore, whereby only a letter is allowed as the first character. The German special characters are not allowed in names. A semicolon follows immediately. You can say that PASCAL loves semicolons. It is always set when commands or definitions have to be separated from one another. All agreements - so-called declarations - of variables and other names must be between the line PROGRAM Name; and the word BEGIN. The word BEGIN announces the executable part of the program. Every BEGIN always has a word END. In between are the commands in the order in which they will be executed later. At the end of a program there must be a period after the END so that the compiler knows that the program is finished here.

PROGRAM program name; (* This program is meant to be tried out *) VAR Name: String [30]; BEGIN Writeln ('Hello, I'm a small PASCAL program'); Write ('What's your name?'); Readln (name); Write (name); Writeln ('is a beautiful name.'); END.


Several things have been added. The asterisk brackets (* *) contain comments by the programmer in which he can write what he was thinking while programming. The compiler will ignore the content of these brackets when translating.

Input and output

Let's see what the program really does. To do this, we need to examine the commands that come after BEGIN. The Write command writes the content of the brackets on the screen. The Writeln command does the same thing, only appends a carriage return at the end. If only texts are to be output, these are put in inverted commas (apostrophes), just as verbatim speech is put in quotation marks in a book.

The next command asks the future user of the program to make an entry. Readln means: Wait and read what is typed on the keyboard until the carriage return key is pressed. Now PASCAL has to somehow remember what the user has typed. The variable in brackets behind the Readln is used for this.

Write a program that will print the two words "Hello User" on the screen.

Variables and variable types

At the beginning of the program is the line:

This means that PASCAL reserves a piece of memory that is sufficient to store 30 letters. It finds this memory under the term Surname again. If the square brackets are not available on the keyboard, string (.30.) Can be written instead. The program generates on the screen:

Hello, I am a small PASCAL program. What's your name?

The program is now waiting for the user to enter it.

What's your name? Anna Anna is a lovely name.

The letters Anna are now in the space with the name Surname and returned to the screen with the Write (Name) command.

Enter the program shown above, compile it, and run it a couple of times. Try entering a variety of first names.

Variables are memory areas that are reserved to store numbers, letters or strings of letters (also String called) for later use in the program. Since a letter takes up a different space than a floating point number, every variable in PASCAL is identified before it is used. For practice and our course, the following four types of variables (also Types called) sufficient.

Type designation content
INTEGER whole numbers from -32768 to 32767
REAL Floating point numbers. The comma in German corresponds to a point in the English-speaking world.
CHAR can take up a letter
String [10] can contain a string of letters (word or phrase) with a maximum of 10 characters.

Danger: The String type is not a standard PASCAL, but is available in most PASCAL compilers.

In a program, a variable should be created for each type of variable and a value should be entered for each variable and then output again. The program should tell the user beforehand what type of input to make (whole number, letters, etc.).

After the exercise, you notice that the REAL values ​​look strange (instead of 12.95, the screen reads 1.2950000000E + 1). This representation is called exponential notation. The number after the E is the exponent to the base 10. You know this representation very similarly on some pocket calculators. The rule of thumb for reading such numbers is: The comma (in PASCAL the point) is shifted to the right by the number after the E. In most cases, however, it makes more sense to keep the type of display you are used to. For this purpose, when writing or writing after the variable: 8: 2 is written. This means that a total of eight digits are kept free for the output, two of which are used for the decimal places.

PRODUCT: Write a small program that reads the name of the product and the price of the product from the user for a product. The following should then appear on the screen: The product ... costs ... DM.


The assignment

Calculations are carried out in Pascal by assigning the result of a calculation to a variable. The assignment symbol is: =. The statement a: = b assigns the content of the variable b to the variable a. a and b must always be of the same type. Exceptions can be found in the chapter Type conversion functions.

Addition, subtraction and multiplication

In addition to assigning a result, there is also the option of displaying the result of a calculation directly on the screen using Writeln. In any case, the type of calculation must be specified using operators (+, -, *).

+ Adding two values. Example: Sum: = summand + 12;
* Multiplying two values. Example: Amount: = price * number of pieces;
- Subtract two values. Example: Tare: = gross - net;

Two types of division

With division, the possibilities of the two data types differ. REAL is also able to record a fraction. Accordingly, the division for REAL variables is:

/ Division. Example: Consumption: = gasoline / kilometer;

It is more difficult with INTEGER variables. A representation of 3.5 as a result does not work. So with the division only the whole number part becomes the result. There is another operator for this, which identifies the remainder of a number that can no longer be divided.

DIV Division. Ex: Result: = 7 DIV 2; The result is 3!
MOD Remainder of a division. Ex: remainder: = 7 MOD 2; The result is the remainder of dividing 7 and 2, which is 1.

Type conversion functions

If variables of different types are linked with one another, the types must be adjusted to one another in PASCAL. So one type has to be transformed into another. The following conversions are important:

No command is required for this. Pascal does this automatically when required. There are no problems here either, since every INTEGER number has an equivalent REAL number.

When converting a REAL number into an integer, the value loses information. PASCAL asks the programmer to indicate how this should be done. There are two options:
TRUNC (value)
The decimal places are cut off.
ROUND (value)
This corresponds to the commercial rounding. If there is a number from 5 to 9 after the decimal point, the value in front of the decimal point is increased by one.

Function CHR (48) generates the letter '0'.

Function ORD ('A') generates the number 65.

Other arithmetic operations

There are still some arithmetic operations. Functions such as sine (SIN (x)) or roots (SQRT (x)) are already defined in the standard PASCAL. For an introduction, it makes little sense to delve into this area, since the normal user rarely needs these mathematical functions. If necessary, reference is made to the further literature and the manuals for the respective implementation of PASCAL.

Program MULTI, which reads in two numbers from the user, multiplies them and outputs the result. If you finish faster, you should change the program to addition, subtraction and division.
PRODUCT: Expand the program in such a way that the quantity of the products is also specified and the price of this quantity is output. Finally, the VAT can also be added. Faster students can also have the user enter the VAT.

Program control commands


It is often necessary to react differently to certain situations. Let's take the entry of prices when placing an order as an example. It is nonsense to allow negative prices. Although negative quantities are not useful either, this option can still be useful in order to also be able to process complaints. Such a distinction basically has the following appearance:

If the price is positive, we will calculate the total price. Otherwise, the user made an incorrect entry

The otherwise branch can also be omitted. The Pascal notation is:

IF condition THEN Tuwas ELSE Tuanderes;

It is important here that there is no semicolon in front of the ELSE. Since a semicolon always separates two statements, a semicolon at this point would separate the ELSE branch from the associated IF. The above example as a PASCAL program part:

IF price> = 0 THEN total: = total + price ELSE Writeln ('Wrong entry ...');

If one command is not sufficient, several commands can be given. They must then be bracketed with BEGIN and END to show PASCAL that these commands belong together. E.g.:

IF set <0 THEN BEGIN Writeln ('A negative set is probably the last thing!'); Writeln ('What do you have to say to justify yourself?'); Readln (Lassihnschwaetzen); Writeln; Writeln ('That's a stupid excuse!'); END;

The following symbols are used to compare two values:

= the first value must be the same as the second.
< > the first value must be different from the second.
< the first value must be smaller than the second.
> the first value must be greater than the second.
< = the first value must be less than the second or the values ​​must be the same.
> = the first value must be greater than the second or the values ​​must be equal.
The MULTI program is to be changed so that only positive numbers are calculated.
PRODUCT: The program should only calculate the total price if the price is not negative.


It is not enough to make a distinction under one condition. Often things have to be done multiple times. This construction is called in the EDP loop. A termination condition must be formulated for each loop, otherwise a program will not come to an end. An error in this condition leads to the dreaded infinite loop.


A program shouldn't give up just because the user has made a mistake. He should be given the opportunity to improve. In the following, the user should enter the price until he has entered a positive number.

Repeat User should enter price until price is positive

In PASCAL, such a construction has the following appearance:

REPEAT Write ('What can it cost?'); Readln (price); UNTIL price> = 0;

The commands between REPEAT and UNTIL are repeated until the condition after UNTIL is met. Such a construct is called a loop.

PRODUCT: Now let the user enter the price until it is positive. The faster ones can do the same loop for the delivery amount.
The program ZAEHL should count. At the beginning the user should enter how far it should be counted. Then all numbers should be displayed one below the other on the screen. If you finish faster, you should also ask the user for the initial value.
The RATE program is supposed to be a little game. The user enters a number until he guesses the number given in the program.


There are three things to keep in mind when doing the NUMBER exercise:

  • The counting variable must be set to the start value before the loop starts.
  • The counting variable must be increased by one each time within the loop.
  • The counting variable must be correctly compared with the upper limit.

Each of these points is a source of error that can lead to the dreaded infinite loop. An infinite loop is a loop in which the end condition never occurs and so never stops running.

Since counting is needed more often, there is a special loop for this purpose. This is made up of the components shown above:

FOR variable :=Starting value TO Upper limit DO Do something

Whenever something has a certain number of repetitions or when something is counted, this loop will be the first choice. Inside a loop contains the variable the current value.

The program ZAEHL looks like this with the help of the FOR loop:

PROGRAM NUMBER; VAR i, final number: INTEGER; BEGIN Write ('How far should I count?'); Readln (final number); FOR i: = 1 TO final number DO Writeln (i); END.

As with the IF, only one command is to be specified by default with the FOR. If you want to loop over several commands, you can use BEGIN END brackets.

Write a program that calculates the sum of the first hundred numbers (i.e. 1 + 2 + 3 + 4 ...).
Write a COMPOUND INTEREST program that creates a compound interest table for the next ten years. The year is on the left in every line, the current capital including interest is shown on the right.


PASCAL supplements the loop form WHILE DO so that the condition is at the beginning of the loop. Since the REPEAT UNTIL loop is sufficient for our purposes, the WHILE DO loop is not discussed further here.

Combination of several constructs

A nesting of several loops and distinctions are possible. So it is possible to repeat only under a certain condition or to nest several loops inside each other, if z. B. the prices should be entered for several products and each individual entry should be repeated until the price is positive. Another example will be presented here. It is deliberately kept quite complex.

To determine the total points of a student, a point value must be entered for each task (FOR loop). The entry of the point value is repeated until it becomes positive (REPEAT loop). The point value is only added up if it is positive (IF distinction). Otherwise a warning message appears on the screen (ELSE branch).

PROGRAM class work; VAR i, tasks: INTEGER; Total points, points: INTEGER; BEGIN Write ('Number of tasks:'); Readln (tasks); Total points: = 0; FOR i: = 1 TO tasks DO BEGIN REPEAT Write ('Task No.'); Write (i); Write (':'); Readln (dots); IF points> = 0 THEN total points: = total points + points ELSE Writeln ('Only positive points ...'); UNTIL points> = 0; END; (* FOR *) Writeln; Write ('The student has'); Write (total points); Writeln ('Points'); END.
We want to change the COMPOUND INTEREST program so that it only displays compound interest every ten years. If you finish faster, you can check whether the year is positive or let the user specify the yearly interval at which the output should take place.
The PRODUCT program is to be expanded in such a way that when a negative price is entered, a warning message appears that prompts the user to make a new entry.
Add to the RATE program so that after each attempt by the user to guess whether the guess is too high or too low is displayed on the screen.

Logical links

As you can see, the value of certain variables can be used to influence the program flow.Sometimes there are cases that depend not only on the state of a variable, but on several conditions. We also know this in everyday life. You are only allowed to drive a car if you have a driver's license on the one hand and are not drunk on the other.


If both a condition and another have to occur, this can be linked with AND. In particular, if limited areas are to be considered, the AND link should be used. In PASCAL this is noted as follows:

IF (price> 100) AND (price <500) THEN Writeln ('The price is okay') ELSE Writeln ('Extreme price');

It should be noted that the ELSE branch is reached both if the price is at most 100 and if the price is at least 500. When looking at it, it is noticeable that the individual conditions are bracketed. This is fundamentally necessary for all logical links.

Different variables can of course also be linked. One could formulate a condition that says that a product is only bought if the price is at most 1,000 and the budget is at least 2,000, as follows:

IF (Price <= 1000) AND (Budget> = 2000) THEN Writeln ('Buy') ELSE Writeln ('Let stand');


If at least one of several conditions is sufficient, this is described in PASCAL with the word OR (or). The condition applies if one of the two partial conditions applies or if both apply. So it does not correspond to the either / or.

The OR link is often used in connection with loops, which can be ended not only at the end of the work, but also by user query. So could z. For example, a computer game that stops after 100 seconds, unless the player has canceled it by pressing the Q key, will have a loop that looks like this:

REPEAT .... UNTIL (seconds> = 100) OR (key = 'q');

Querying several keys is also a typical or problem. The query, which allows the capital Q as well as the small q, looks like this:

IF (key = 'q') OR (key = 'Q') THEN ....


If the opposite of a condition is to be considered, the overall condition can be bracketed and preceded by NOT. The implementation of a condition is not always trivial. So it is still clear that the opposite of days> = 20 days <20 is. On the other hand, negating the following line requires some thought.

IF (salary> = 1000) AND (salary <3000) THEN ...

The opposite of the individual conditions is still clear. Instead of> = is used <, instead of =. But the AND cannot remain as it is, otherwise the content must be less than 1000 and at least 3000. Obviously you can't. The correct link here is OR.

IF (salary <1000) OR (salary> = 3000) THEN ...

Data type fields (ARRAY)

In practice, there is often the problem that not only one value has to be stored, but that there are several copies of one type. For example, a mail order company will sell a lot of products, a hotel will have a lot of rooms, and so on. If there are several specimens of the same variety, they can be numbered and addressed with the help of its number. For example, a hotel has a number for each room. If I know the room number, I can look up who lives there in the occupancy list.

In order to be able to reproduce this in Pascal, you can create a so-called ARRAY. Name the variable and define it as an ARRAY of its type:

VAR variable : ARRAY [1..20] OF Type ;

As an example, let us consider a retailer who would have liked to save the prices of his products and would have always liked to output the price on the product number. At the beginning, the price must be given for each product. When selling, he just has to enter the number and he sees the price on the screen.

PROGRAM product; VAR price: ARRAY [1..20] OF REAL; i, number, number: INTEGER; BEGIN (* Enter all product prices *) Write ('How many products:'); Readln (number); FOR i: = 1 TO number DO BEGIN Write ('Product'); Write (i); Write ('costs:'); Readln (price [i]); END; (* FOR *) (* Selling begins ... *) REPEAT Write ('Product number:'); Readln (number); IF number> 0 THEN BEGIN Write ('Product'); Write (number); Write ('costs'); Writeln (price [number]); END; (* IF *) UNTIL number = 0; END.
Extend the Product program so that the names of the products are also recorded.

We have actually known such ARRAYs from the start. The String type also has the square brackets at the end, which indicate that this was once an array.

String [20] corresponded to ARRAY [1..20] OF CHAR

Originally, PASCAL was also defined in such a way that character strings had to be processed in this way. This has been changed, because otherwise Readln and Writeln would have to be programmed by yourself.

Write a HOTEL program that manages the room occupancy of a hotel. The hotel has 10 rooms. An empty room is indicated by a series of minus signs. The user receives the room occupancy after each entry. He can enter a room number, then the new name. This is entered as a new occupancy and the user receives the room occupancy again. If the room number 0 is entered, the program is ended.

Subroutines (PROCEDURE)

Procedures offer the option of combining several commands into one task and calling them up like a new command. So you can define your own commands and later call them up as often as you like.

First you think of a name for the new command to be created. A small program is then created that contains exactly the commands that our new command should be able to handle. The new procedure has a very similar structure to a PASCAL program, only that it is called PROCEDURE instead of PROGRAM. For this reason, procedures are often called subroutines.

PROGRAM stars; VAR i: INTEGER; Star number: INTEGER; PROCEDURE MachMieleStars; VAR i: INTEGER; BEGIN FOR i: = 1 TO star number DO Write ('*'); Writeln; END; BEGIN (* This is where the program starts *) Writeln ('Many, many stars .....'); Star number: = 77; FOR i: = 1 TO 10 DO MachManyStars; END.

The procedures are defined after the variable declaration and before the BEGIN of the main program. The definition of the MachVieleSterne procedure itself does not cause any activities. The procedure only starts when the MachVieleSterne command is called. So 10 lines with 77 stars each are output.

The use of the variable i is also interesting. The procedure has its own private variable i. This does not change the variable i of the main program. Both loops do not interfere with each other. A variable that is used by the subroutine and the program represents the star number. The main program defines how many stars should appear per line. From the point of view of the procedure, i is called a local variable and the star number is called a global variable. A local variable is forgotten again after exiting a procedure. So it is only used for short-term storage.

PRODUCT: Entering a product has slowly become more convenient, but also more confusing. A product name and a price are entered. The price is checked whether it is positive. We can now define a command that does all of these.
Compound Interest Table: The entry is created as a procedure. If you are faster, you convert the calculation and output into a procedure. This means that the main program should only contain input, processing, and output.

Top-down programming

Let us consider the example of a street vendor who sells sandals and the foot ointment later required by using the sandals. In the morning he sets the respective price for the ointment and for the sandals based on the experiences of the last day or depending on the weather. Now people come and buy x sandals and y tubes of foot ointment. The computer is supposed to calculate the total for the people at the checkout and report the sales in the evening.

Set prices
Purchased quantity by a customer
Create customer invoice
Users ask if it's already finished
until user response = 'y'
Throw out sales

A main program is written directly in PASCAL from this flow chart:

PROGRAM street seller; VAR response: CHAR; (* Variable is used for the user's answer to the question about the end of the program. *) BEGIN Enter prices; Enter REPEAT sales quantity; Customer invoice; Is already holiday evening; UNTIL answer = 'y'; Sales eject; END.

The procedures Enter Prices, Enter Sales Amount, CustomerInvoicing, Actual Holidays and SalesEject must now be written. It turns out that the procedures Enter Prices, Enter Sales Amount and IstSchonFeierabend each consist of only one Write and one Readln. The read-in variables must be specified above when used. The customer invoice procedure is a little more demanding, but not problematic:

PROCEDURE customer invoice; VAR cash value: REAL; BEGIN cash value: = sandals quantity * sandals price; Cash value: = Cash value + (Ointment Amount * Ointment Price); Write ('The customer owes:'); Writeln (KassenWert); END;

Only when calculating the turnover has to be considered again. Sales must be zero at the beginning of the day. The calculated amount must be added to sales for each sale. At the end of the day, the turnover must be displayed. The solution consists in defining a global variable turnover, assigning it the value 0 after the BEGIN or in price entries, in customer invoices the cash value through sales: = sales + cash value; open and in the procedure SalesEject this variable with Writeln on the screen.

The BUCHHANDEL program is designed to support a book seller who only sells one book. At the beginning of the day, he sets the price of his book for today. During the day, customers come and buy books. Only the number of books should be entered and the program should determine the price.

Compounds (RECORD)

So far we have had two independent variables for each product. But the price and name of a product belong together to a product. The stock in the warehouse may still belong to the product. A product type can be created for this purpose.
TYPE ProductType = RECORD Name: String [30]; Price: REAL; Stock: REAL; END; VAR Product: ProductType; BEGIN ReadLn (Product.Name); ReadLn (Product.Price);

You can add your own type types to the variable types such as INTEGER, REAL and String. For this purpose, a new type name is agreed with TYPE and what it looks like is defined after the equal sign. Groups are defined between RECORD and END. The components are listed and the type is written after a colon, as in the variable declaration. The names in front of the colon are used for later access to the individual components. In the variable declaration it is easy to see that the definition of a variable with its own type works in the same way as with the standard types. Behind the BEGIN you can see an example of how such a network is accessed. The variable name is mentioned first. Then a period is set as a sign that the substructure is being accessed and the name of the substructure as it is listed in the type definition is given last.

An empty program is created in which the Date type is defined. A date must consist of a day, month and year. The variables today, tomorrow and the day after tomorrow are to be declared of this type. The date should then be entered once and then written back to the screen.

More complex types can be composed of simpler types. For example:

TYPE Person = RECORD Name: String [20]; Apartment: address; born: date; END;

Pascal now knows neither the date nor the address. So, before defining Person, a date type and an address type must be defined. How the date is created has already been seen in the exercise. The address type could now look like this:

TYPE date = RECORD day, month, year: INTEGER; END; Address = RECORD Street: String [20]; ZIP: INTEGER; Location: String [20]; END; Person = RECORD Name: String [20]; Apartment: address; born: date; END; VAR Meier, Mueller: person;

The output of the place of residence of the person Mueller would look like this:

Writeln (Mueller.Apartment.Ort);

So there is a point after the variable name. The object then follows under the name that is used in the type definition. If this is also a RECORD, the name from this type definition is used again.

Mixing type constructs

We had already seen how to model products with the help of RECORDs. We had also seen how many prices can be saved with the help of an ARRAY. It is interesting for a retailer to create an ARRAY of the modeled product in order to e.g. B. to be able to represent a range of products. To do this, a product is first modeled and an ARRAY is defined from it. We see this in the following example:
PROGRAM orders; TYPE ProductType = RECORD Name: String [30]; Price: REAL; Stock: REAL; END; PalettenTyp = ARRAY [1..200] OF ProductType; VAR product: pallet type;

In the example, the name, price and stock of product number 27 should now be displayed on the screen. To do this, the following commands must be given in the program:

Writeln (Product [27] .Name); Writeln (Product [27]. Price: 8: 2); Writeln (Product [27]. Stock: 8: 0);
Write a loop that reads the name, price and supply from the keyboard for the first five products.

Procedures with parameters

In order to be able to use a procedure for several objects, it should be possible to tell it that it can use any variable of this type. So you could write commands that behave like Pascal commands. This means that our command only contains how it should do its work, but not with which variables. The variables are passed to him later when it is used. This all sounds complicated at first, but we haven't used anything else all along:
PROGRAM output; VAR OneNumber, AnotherNumber: INTEGER; BEGIN Writeln (a number); Writeln (NochNeZahl); END.

We took it for granted that Writeln itself knows that it should output the variable ANumber in the first line and AnotherNumber in the second line. We want to extend the well-known MachVieleSterne procedure so that you can tell it when it is called how many stars it should produce.

PROGRAM stars; VAR i: INTEGER; PROCEDURE MachVieleSterne (StarNumber: INTEGER); VAR i: INTEGER; BEGIN FOR i: = 1 TO star number DO Write ('*'); Writeln; END; BEGIN (* This is where the program starts *) Writeln ('Many, many stars .....'); MachManyStar (77); (* constant number *) FOR i: = 1 TO 10 DO MachVieleSterne (i); (* Value determines a variable *) END.