Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Learn Pascal.pdf, Lecture notes of Compilers

This tutorial is an introduction to the Pascal simple, yet complete, introduction to the Pascal programming language. It covers all of the syntax of.

Typology: Lecture notes

2021/2022

Uploaded on 09/27/2022

merielynd
merielynd 🇬🇧

4.7

(9)

218 documents

1 / 46

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e

Partial preview of the text

Download Learn Pascal.pdf and more Lecture notes Compilers in PDF only on Docsity!

Index

  • Introduction
  • History of Pascal
  • Pascal Compilers
  • Hello, world.
  • Basics o Program Structure o Identifiers o Constants o Variables and Data Types o Assignment and Operations o Standard Functions o Punctuation and Indentation o Programming Assignment o Solution
  • Input/Output o Input o Output o Formatting output o Files o EOLN and EOF o Programming Assignment o Solution
  • Program Flow o Sequential control o Boolean Expressions o Branching  IF  CASE o Looping  FOR..DO  WHILE..DO  REPEAT..UNTIL o Programming Assignments: Fibonacci Sequence and Powers of Two o Solutions
  • Subprograms o Procedures o Parameters o Functions o Scope o Recursion o Forward Referencing o Programming Assignment: the Towers of Hanoi o Solution
  • Data types o Enumerated types o Subranges o 1-dimensional arrays o Multidimensional arrays o Records o Pointers
  • Final words

History of Pascal

Origins

Pascal grew out of ALGOL, a programming language intended for scientific computing. Meeting in Zurich, an international committee designed ALGOL as a platform-independent language. This gave them comparatively free rein in the features they could design into ALGOL, but also made it more difficult to write compilers for it. Those were the days when many computers lacked hardware features that we now take for granted. The lack of compilers on many platforms, combined with its lack of pointers and many basic data types such as characters, led to ALGOL not being widely accepted. Scientists and engineers flocked to FORTRAN, a programming language which was available on many platforms. ALGOL mostly faded away except as a language for describing algorithms.

Wirth Invents Pascal

In the 1960s, several computer scientists worked on extending ALGOL. One of these was Dr. Niklaus Wirth of the Swiss Federal Institute of Technology (ETH-Zurich), a member of the original group that created ALGOL. In 1971, he published his specification for a highly- structured language which resembled ALGOL in many ways. He named it Pascal after the 17th-century French philosopher and mathematician who built a working mechanical digital computer. Pascal is very data-oriented, giving the programmer the ability to define custom data types. With this freedom comes strict type-checking, which prevented data types from being mixed up. Pascal was intended as a teaching language, and was widely adopted as such. Pascal is free-flowing, unlike FORTRAN, and reads very much like a natural language, making it very easy to understand code written in it.

UCSD Pascal

One of the things that killed ALGOL was the difficulty of creating a compiler for it. Dr. Wirth avoided this by having his Pascal compiler compile to an intermediate, platform- independent object code stage. Another program turned this intermediate code into executable code. Prof. Ken Bowles at the University of California at San Diego (UCSD) seized on the opportunity this offered to adapt the Pascal compiler to the Apple II, the most popular microcomputer of the day. UCSD P-System became a standard, and was widely used at universities. This was aided by the low cost of Apple II's compared to mainframes, which were necessary at the time to run other languages such as FORTRAN. Its impact on computing can be seen in IBM's advertisements for its revolutionary Personal Computer, which boasted that the PC supported three operating systems: Digital Research's CP/M- 86, Softech's UCSD P-system, and MicroSoft's PC-DOS.

Pascal Becomes Standard

By the early 1980's, Pascal had already become widely accepted at universities. Two events conspired to make it even more popular. First, the Educational Testing Service, the company which writes and administers the principal college entrance exam in the United States, decided to add a Computer Science exam to its Advanced Placement exams for high school students. For this exam, it chose the Pascal language. Because of this, secondary-school students as well as college

students began to learn Pascal. Pascal remained the official language of the AP exams until 1999, when it was replaced by C++, which was quickly replaced by Java. Second, a small company named Borland International released the Turbo Pascal compiler for the IBM Personal Computer. The compiler was designed by Anders Hejlsberg, who would later head the group at Microsoft that developed C# and (re)introduced Managed Code back to the world of computing. Turbo Pascal was truly revolutionary. It did take some shortcuts and made some modifications to standard Pascal, but these were minor and helped it achieve its greatest advantage: speed. Turbo Pascal compiled at a dizzying rate: several thousand lines a minute. At the time, the available compilers for the PC platform were slow and bloated. When Turbo Pascal came out, it was a breath of fresh air. Soon, Turbo Pascal became the de facto standard for programming on the PC. When PC Magazine published source code for utility programs, it was usually in either assembly or Turbo Pascal. At the same time, Apple came out with its Macintosh series of computers. As Pascal was the preeminent structured programming language of the day, Apple chose Pascal as the standard programming language for the Mac. When programmers received the API and example code for Mac programming, it was all in Pascal.

Extensions

From version 1.0 to 7.0 of Turbo Pascal, Borland continued to expand the language. One of the criticisms of the original version of Pascal was its lack of separate compilation for modules. Dr. Wirth even created a new programming language, Modula-2, to address that problem. Borland added modules to Pascal with its units feature. By version 7.0, many advanced features had been added. One of these was DPMI (DOS Protected Mode Interface), a way to run DOS programs in protected mode, gaining extra speed and breaking free of the 640K barrier for accessing memory under DOS. Turbo Vision, a text-based windowing system, allowed programmers to create great-looking interfaces in practically no time at all. Pascal even became object-oriented, as version 5. adopted the Apple Object Pascal extensions. When Windows 3.0 came out, Borland created Turbo Pascal for Windows, bringing the speed and ease of Pascal to the graphical user interface. It seemed that Pascal's future was secure.

The World Changes

However, this was not to be. In the 1970s, Dennis Ritchie and Brian Kernighan of AT&T Bell Laboratories created the C Programming Language. Ritchie then collaborated with Ken Thompson to design the UNIX operating system. At the time, AT&T had a government-sanctioned monopoly on telephone service in the United States. In return for the monopoly, its telephone business was regulated and it was prohibited from entering the computer business. AT&T, seeing no market for a research operating system, gave UNIX away to universities for free, complete with source code. Thus, a whole generation of computer science students learned C in their university courses on languages and operating systems. Slowly but surely, C began to filter into the computer programming world. Pascal was finally killed by object orientation and the move to Windows on the industry- standard PC platform. In the 1980s, Bjarne Stroustrop, also of Bell Labs, popularized object-orientation by developing C++, which kept the familiar syntax of C while extending it for object orientation. C++ came to define object orientation to a generation of programmers, and remains a strong force even today. Also in the 1980s, Microsoft Windows adopted C as its standard programming language. In contrast to MacOS and Pascal, the Windows API samples were all in K&R (pre-ANSI)

Pascal Compilers

This document will explain the basics about compilers as well as provide links to well- known Pascal compilers and explain how to set up Free Pascal.

About Computer Languages and Compilers

When talking about computer languages, there are basically three major terms that will be used.

  1. Machine language -- actual binary code that gives basic instructions to the computer's CPU. These are usually very simple commands like adding two numbers or moving data from one memory location to another.
  2. Assembly language -- a way for humans to program computers directly without memorizing strings of binary numbers. There is a one-to-one correspondance with machine code. For example, in Intel x86 machine language, ADD and MOV are mnemonics for the addition and move operations.
  3. High-level language -- permits humans to write complex programs without going step-by step. High-level languages include Pascal, C, C++, FORTRAN, Java, BASIC, and many more. One command in a high-level language, like writing a string to a file, may translate to dozens or even hundreds of machine language instructions. Microprocessors can only run machine language programs directly. Assembly language programs are assembled , or translated into machine language. Likewise, programs written in high-level languages, like Pascal, must also be translated into machine language before they can be run. To do this translation is to compile a program. The program that accomplishes the translation is called a compiler. This program is rather complex since it not only creates machine language instructions from lines of code, but often also optimizes the code to run faster, adds error-correction code, and links the code with subroutines stored elsewhere. For example, when you tell the computer to print something to the screen, the compiler translates this as a call to a pre-written module. Your code must then be linked to the code that the compiler manufacturer provides before an executable program results. With high-level languages, there are again three basic terms to remember:
  4. Source code -- the code that you write. This typically has an extension that indicates the language used. For example, Pascal source code usually ends in ".pas" and C++ code usually ends in ".cpp"
  5. Object code -- the result of compiling. Object code usually includes only one module of a program, and cannot be run yet since it is incomplete. On DOS/Windows systems, this usually has an extension of ".obj"
  6. Executable code -- the end result. All the object code modules necessary for a program to function are linked together. On DOS/Windows systems, this usually has an extension of ".exe"

More About Compilers

The de facto standard in DOS and Windows-based compilers is Borland Pascal. Before it came out, most Pascal compilers were clumsy and slow, strayed from the Pascal standard, and cost several hundred dollars. In 1984, Borland introduced Turbo Pascal, which sold for less than $100, compiled an order of magnitude faster than existing compilers, and came with an abundance of source code and utility programs. This product was a great success and was prominent for almost a decade. But in the 1990s, the world was moving to Windows. In 1993, the last version of Turbo Pascal, version 7 for DOS, came out. After that, the demand for DOS programs plummetted and Borland (renamed Inprise, then back to Borland) focused on producing Windows compilers. This tutorial will only deal with console-based programming, where the computer prints lines of data to the screen and the user interacts with the program using a keyboard. The goal of the tutorial is to teach how to program in Pascal. Once you've learned that, you can easily look at a reference book or another web page and pick up graphics and windowing systems on your own. Although old commercial Pascal compilers are often available for download, Turbo Pascal 5.5 from the Borland Museum and Symantec Think Pascal (Macintosh) linked from The Free Country's Free Pascal Compiler List, computers have progressed much since the 1980s and early 1990s. We are no longer stuck with 8.3 filenames on DOS or non- preemptive multitasking on Mac OS. Using an old compiler is fun in the same sense as playing an old game on an emulator, but the open source movement has produced good compilers for modern operating systems, and a beginner will find it much easier to use those.

Open Source Compilers

The two main open-source compiler projects are:

  • GNU Pascal
  • Free Pascal Free Pascal is generally considered friendlier for novices, and strives to emulate Borland Pascal in many ways, though both will serve fine for learning Pascal. As most users of this tutorial will be running Windows, here's how to set up Free Pascal and get to the point where you're compiling a program on a modern Windows operating system:
  1. Download the Win32 installer for Free Pascal from the Free Pascal download page.
  2. Run the file you just downloaded and go through the wizard to setup Free Pascal.
  3. Open Free Pascal using the shortcut (by default it is located in Start → Free Pascal.
  4. Type in a program (flip to the next lesson to get a "Hello, world." program).
  5. Save the file with File-Save As ...
  6. Run the program from the Run menu. This will automatically compile the program if you've made any changes, then run the program. It will also run the program without compiling if you've not made any changes since the last time you compiled.

Hello, world.

In the short history of computer programming, one enduring tradition is that the first program in a new language is a "Hello, world" to the screen. So let's do that. Copy and paste the program below into your IDE or text editor, then compile and run it. If you have no idea how to do this, return to the Table of Contents. Earlier lessons explain what a compiler is, give links to downloadable compilers, and walk you through the installation of an open-source Pascal compiler on Windows. program Hello; begin (* Main ) writeln ('Hello, world.') end. ( Main ) The output on your screen should look like: Hello, world. If you're running the program in an IDE, you may see the program run in a flash, then return to the IDE before you can see what happened. See the bottom of the previous lesson for the reason why. One suggested solution, adding a readln to wait for you to press Enter before ending the program, would alter the "Hello, world" program to become: program Hello; begin ( Main ) writeln ('Hello, world.'); readln end. ( Main *)

Basics

The basic structure of a Pascal program is: PROGRAM ProgramName ( FileList ) ; CONST (* Constant declarations *) TYPE (* Type declarations *) VAR (* Variable declarations ) ( Subprogram definitions *) BEGIN (* Executable statements *) END. The elements of a program must be in the correct order, though some may be omitted if not needed. Here's a program that does nothing, but has all the required elements: program DoNothing ; begin end. Comments are portions of the code which do not compile or execute. Pascal comments start with a (* and end with a ). You cannot nest comments: ( ( ) ) will yield an error because the compiler matches the first ( with the first ) , ignoring the second ( which is between the first set of comment markers. The second ) is left without its matching (. This problem with begin-end comment markers is one reason why many languages use line-based commenting systems. Turbo Pascal and most other modern compilers support brace comments, such as { Comment }. The opening brace signifies the beginning of a block of comments, and the ending brace signifies the end of a block of comments. Brace comments are also used for compiler directives. Commenting makes your code easier to understand. If you write your code without comments, you may come back to it weeks, months, or years later without a guide to why you coded the program that way. In particular, you may want to document the major design of your program and insert comments in your code when you deviate from that design for a good reason. In addition, comments are often used to take problematic code out of action without deleting it. Remember the earlier restriction on nesting comments? It just so happens that braces {} take precedence over parentheses-stars (* ). You will not get an error if you do this: { ( Comment *) }

Constants are referenced by identifiers, and can be assigned one value at the beginning of the program. The value stored in a constant cannot be changed. Constants are defined in the constant section of the program: const Identifier1 = value ; Identifier2 = value ; Identifier3 = value ; For example, let's define some constants of various data types: strings, characters, integers, reals, and Booleans. These data types will be further explained in the next section. const Name = 'Tao Yue'; FirstLetter = 'a'; Year = 1997; pi = 3.1415926535897932; UsingNCSAMosaic = TRUE; Note that in Pascal, characters are enclosed in single quotes, or apostrophes (')! This contrasts with newer languages which often use or allow double quotes or Heredoc notation. Standard Pascal does not use or allow double quotes to mark characters or strings. Constants are useful for defining a value which is used throughout your program but may change in the future. Instead of changing every instance of the value, you can change just the constant definition. Typed constants force a constant to be of a particular data type. For example, const a : real = 12; would yield an identifier a which contains a real value 12.0 instead of the integer value 12. Variables are similar to constants, but their values can be changed as the program runs. Variables must first be declared in Pascal before they can be used: var IdentifierList1 : DataType1 ; IdentifierList2 : DataType2 ; IdentifierList3 : DataType3 ; ... IdentifierList is a series of identifiers, separated by commas (,). All identifiers in the list are declared as being of the same data type. The basic data types in Pascal include:

  • integer
  • real
  • char
  • Boolean Standard Pascal does not make provision for the string data type, but most modern compilers do. Experienced Pascal programmers also use pointers for dynamic memory allocation, objects for object-oriented programming, and many others, but this gets you started. More information on Pascal data types:
  • The integer data type can contain integers from -32768 to 32767. This is the signed range that can be stored in a 16-bit word, and is a legacy of the era when 16-bit CPUs were common. For backward compatibility purposes, a 32-bit signed integer is a longint and can hold a much greater range of values.
  • The real data type has a range from 3.4x10-38^ to 3.4x10^38 , in addition to the same range on the negative side. Real values are stored inside the computer similarly to scientific notation, with a mantissa and exponent, with some complications. In Pascal, you can express real values in your code in either fixed-point notation or in scientific notation, with the character E separating the mantissa from the exponent. Thus, 452.13 is the same as 4.5213e
  • The char data type holds characters. Be sure to enclose them in single quotes, like so: 'a' 'B' '+' Standard Pascal uses 8-bit characters, not 16-bits, so Unicode, which is used to represent all the world's language sets in one UNIfied CODE system, is not supported.
  • The Boolean data type can have only two values: TRUE and FALSE An example of declaring several variables is: var age, year, grade : integer; circumference : real; LetterGrade : char; DidYouFail : Boolean; Once you have declared a variable, you can store values in it. This is called assignment. To assign a value to a variable, follow this syntax: variable_name := expression ; Note that unlike other languages, whose assignment operator is just an equals sign, Pascal uses a colon followed by an equals sign, similarly to how it's done in most computer algebra systems. The expression can either be a single value: some_real := 385.385837; or it can be an arithmetic sequence: some_real := 37573.5 * 37593 + 385.8 / 367.1;

some_real := 37.5 * (-2); The computer follows an order of operations similar to the one that you follow when you do arithmetic. Multiplication and division (* / div mod) come before addition and subtraction (+ -), and parentheses always take precedence. So, for example, the value of: 3.5*(2+3) will be 17.5. Pascal cannot perform standard arithmetic operations on Booleans. There is a special set of Boolean operations. Also, you should not perform arithmetic operations on characters. Pascal has several standard mathematical functions that you can utilize. For example, to find the value of sin of pi radians: value := sin (3.1415926535897932); Note that the sin function operates on angular measure stated in radians, as do all the trigonometric functions. If everything goes well, value should become 0. Functions are called by using the function name followed by the argument(s) in parentheses. Standard Pascal functions include: Function Description Argument type Return type abs absolute value real or integer same as argument arctan arctan in radians real or integer real cos cosine of a radian measure real or integer real exp e^ to the given power^ real or integer real ln natural logarithm real or integer real round round to nearest integer real integer sin sin of a radian measure real or integer real sqr square (power 2) real or integer same as argument sqrt square root (power 1/2) real or integer real trunc truncate (round down) real or integer integer For ordinal data types (integer or char), where the allowable values have a distinct predecessor and successor, you can use these functions: Function Description Argument type Return type chr character with given ASCII integer char

value ord ordinal value integer or char integer pred predecessor integer or char same as argument type succ successor integer or char same as argument type Real is not an ordinal data type! That's because it has no distinct successor or predecessor. What is the successor of 56.0? Is it 56.1, 56.01, 56.001, 56.0001? However, for an integer 56 , there is a distinct predecessor — 55 — and a distinct successor — 57. The same is true of characters: 'b' Successor: 'c' Predecessor: 'a' The above is not an exhaustive list, as modern Pascal compilers include thousands of functions for all sorts of purposes. Check your compiler documentation for more. Since Pascal ignores end-of-lines and spaces, punctuation is needed to tell the compiler when a statement ends. You must have a semicolon following:

  • the program heading
  • each constant definition
  • each variable declaration
  • each type definition (to be discussed later)
  • almost all statements The last statement in a BEGIN-END block, the one immediately preceding the END, does not require a semicolon. However, it's harmless to add one, and it saves you from having to add a semicolon if suddenly you had to move the statement higher up. Indenting is not required. However, it is of great use for the programmer, since it helps to make the program clearer. If you wanted to, you could have a program look like this: program Stupid; const a=5; b=385.3; var alpha,beta:real; begin alpha := a + b; beta:= b / a end. But it's much better for it to look like this: program NotAsStupid; const

As you can see, the default output method for real numbers is scientific notation. Chapter 2 will explain you how to format it to fixed-point decimal. To see one possible solution of the assignment, go to the next page. Here's one way to solve the programming assignment in the previous section. (* Author: Tao Yue Date: 19 June 1997 Description: Find the sum and average of five predefined numbers Version: 1.0 - original version ) program SumAverage; const NumberOfIntegers = 5; var A, B, C, D, E : integer; Sum : integer; Average : real; begin ( Main ) A := 45; B := 7; C := 68; D := 2; E := 34; Sum := A + B + C + D + E; Average := Sum / NumberOfIntegers; writeln ('Number of integers = ', NumberOfIntegers); writeln ('Number1 = ', A); writeln ('Number2 = ', B); writeln ('Number3 = ', C); writeln ('Number4 = ', D); writeln ('Number5 = ', E); writeln ('Sum = ', Sum); writeln ('Average = ', Average) end. ( Main *)

Input/Output

Input is what comes into the program. It can be from the keyboard, the mouse, a file on disk, a scanner, a joystick, etc. We will not get into mouse input in detail, because that syntax differs from machine to machine. In addition, today's event-driven windowing operating systems usually handle mouse input for you. The basic format for reading in data is: read ( Variable_List ); Variable_List is a series of variable identifiers separated by commas. read treats input as a stream of characters, with lines separated by a special end-of-line character. readln, on the other hand, will skip to the next line after reading a value, by automatically moving past the next end-of-line character: readln ( Variable_List ); Suppose you had this input from the user, and a, b, c, and d were all integers. 45 97 3 1 2 3 Here are some sample read and readln statements, along with the values read into the appropriate variables. Statement(s) a b c d read (a); read (b); 45 97 readln (a); read (b); 45 1 read (a, b, c, d); (^45 97 3 ) readln (a, b); readln (c, d); 45 97 1 2 When reading in integers, all spaces are skipped until a numeral is found. Then all subsequent numberals are read, until a non-numeric character is reached (including, but not limited to, a space).

When an integer is read from the above input, its value becomes 8352. If, immediately afterwards, you read in a character, the value would be '.' since the read head stopped at the first alphanumeric character.