






































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
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
1 / 46
This page cannot be seen from the preview
Don't miss anything!
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.
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.
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.
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.
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.
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)
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.
When talking about computer languages, there are basically three major terms that will be used.
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.
The two main open-source compiler projects are:
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 *)
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:
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:
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 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.