pascal

47
Prepared by Michel Barakat 1

Upload: crescent

Post on 25-Jan-2016

44 views

Category:

Documents


0 download

DESCRIPTION

Prepared by Michel Barakat. PASCAL. Preface. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: PASCAL

Prepared by Michel Barakat1

Page 2: PASCAL

Preface A computer is nothing but a very dumb

machine that has the ability to perform mathematical operations very rapidly and very accurately, but it can do nothing without the aid of a program written by a human being. Moreover, if the human being writes a program that turns good data into garbage, the computer will very obediently, and very rapidly, turn the good data into garbage.

2

Page 3: PASCAL

WHAT IS SO GOOD ABOUT PASCAL? Some computer languages allow the programmer

to define constants and variables in a very random manner and then combine data in an even messier manner.

Some programming languages would allow you to do just such an addition and obediently print out the meaningless answer.

Since Pascal requires you to set up your constants and variables in a very precise manner, the possibility of such a meaningless answer is minimized.

3

Page 4: PASCAL

How to write using PASCAL?

The first line is required in the standard Pascal definition and contains the program name which can be any name you like.

The first word program is the first of the reserved words mentioned earlier and it is the indicator to the Pascal compiler that this is the name of the program.

The second word is the program name itself. It could be anything the programmer desires.

Most of the statements in PASCAL end with a semicolon “;”

4

Page 5: PASCAL

Identifiers The identifiers in PASCAL are:

Program name Procedure and functions names Type definitions Constants and variables names

Any combination of alphabetic and numeric characters with no blanks embedded can be used as a name for the identifier, however, the identifier must always start with an alphabetic character.

Upper and lower case characters may be mixed at will.

5

Page 6: PASCAL

The words “begin” and “end” We saw the reserved word program at the beginning of

this tutorial. The two next reserved words are begin and end

These words are used mainly for bracketing. So just like we use “{“ and “}” in JAVA, begin and end are the signal for the compiler in order to know where the operation is starting and ending.

Moreover, in PASCAL, we use the period following the word end (i.e. end.) to let the compiler know that it has reached the end of executable statements and therefore it has to finish compiling.

Every Pascal program will have one, and only one period in it, and that one period will be at the end of the program.

6

Page 7: PASCAL

The word “Writeln”

The special word Writeln is not a reserved word but is defined by the system to do a very special job for you, namely to output a line of data to the monitor.

Writeln('bla bla');

7

Page 8: PASCAL

The word “Write”

Same as “Writeln”, the word “Write” is not a reserved word.

It is designed to output something on the monitor without returning any carriage to the first character of the next line.

Write(‘bla bla');

8

Page 9: PASCAL

Comments Professional programmers uses lots of

commented programs in order to explain the semantics of the code.

To comment in PASCAL, we use either the (* comments inside *) or the{ comments inside }

Some compilers allow to do the following (* comments } or { comments*) but it is considered as one of the bad programming habits.

9

Page 10: PASCAL

Simple Data Types PASCAL introduces us to 8 different data types

integer (Whole numbers from -32768 to 32767)byte (The integers from 0 to 255 )Real (Floating point numbers from 1E-38 to 1E+38)Boolean (Can only have the value TRUE or FALSE)Char (Any character in the ASCII character set)Shortint (The integers from -128 to 127)Word (The integers from 0 to 65535)Longint (The integers from -2147483648 to 2147483647)

10

Page 11: PASCAL

The word var

The reserved word var is used to define a variable before it can be used anywhere in the program.

For example:

var Count : integer;

Total : integer;

Alphabet : char;

11

Page 12: PASCAL

Basic arithmetical operations Just like any other programming

language, the mathematical operators are the same except for the quality sign. In PASCAL, instead of “=“ , we use the “:=“ sign.

So the operations X:=X+1 would be read as X gets the value of X plus 1.

12

Page 13: PASCAL

Relational operators Relational operators are those to compare

any two variables of same type in the program and return the result as a boolean TRUE or FALSE

PASCAL’s relational operators list:= (equal to)<> (not equal to)> (greater than)< (less than)>= (greater than or equal to)<= (less than or equal to)

13

Page 14: PASCAL

Boolean variables

The boolean variable is only allowed to take on two values which are TRUE and FALSE.

We use boolean variables for loop controls, end of file indicators, or any other TRUE or FALSE conditions in the program.

14

Page 15: PASCAL

The words “or” and “and” Mainly, we use those two reserved

words for handling Booleans. It’s either using two boolean expressions with the word and or with the word or

15

and TRUE FALSE

TRUE TRUE FALSE

FALSE FALSE FALSE

or TRUE FALSE

TRUE TRUE TRUE

FALSE TRUE FALSE

Page 16: PASCAL

Loops and control structures

The for LoopThis is used to repeat a single statement any number of times

we desire.Any simple variable of type integer, byte, or char can be

used for the loop index but due to the requirement that everything must be defined prior to use in Pascal, the loop index must be defined in a var statement.

To increment the index, we use the reserved word to. i.e. for Count := 1 to 10 do {this will be the header of a for loop}

As for decrementing, we use the reserved word downto. i.e. for Count := 7 downto 2 do

Following the word do will be a:○ Single statement that will be executed or a○ Compound statement that have to be bracketed with the begin

end pair

16

Page 17: PASCAL

The if statement Any condition that can be reduced to a

Boolean answer is put between the if then pair of words.

If the resulting expression resolves to TRUE, then the single Pascal statement following the reserved word then is executed if it resolves to FALSE, then the single statement is skipped over.

if it resolves to FALSE, then the single statement is skipped over.

As for a compound statement, it have to be bracketed with a begin end pair

17

Page 18: PASCAL

The if then else block The if then else construct is one of the most

used, most useful, and therefore most important aspects of Pascal. And it goes as follows:

if Two = 2 then Writeln(‘bla bla') else Writeln(‘blaaaaaaaaaaa');

18

Page 19: PASCAL

The repeat until loop Two more reserved words are defined here, namely

repeat and until. And it goes like:

var Count : integer; Count := 4;

repeat Write('This is in the '); Write('repeat loop, and '); Write('the index is',Count:4); Writeln; Count := Count + 2; until Count = 20;

19

Page 20: PASCAL

The while loop This uses the while do reserved words and will execute one Pascal

statement (or one compound statement bounded with begin and end) continuously until the boolean expression between the two words becomes FALSE. for example:

var Counter : integer;

begin Counter := 4; while Counter < 20 do begin Write('In the while loop, waiting '); Write('for the counter to reach 20. It is',Counter:4); Writeln; Counter := Counter + 2;

end;end.

20

Page 21: PASCAL

Procedures

Procedures are like methods in JAVA except for that we can define them as simple as the following:procedure Write_My_Name;

begin

Writeln('This is my name: Michel');

end;

As for calling a procedure, we simply need to state its name.

21

Page 22: PASCAL

Procedures can also be called by reference or by value. But they have to be first defined in a way to be called in a such way. i.e. By value:

var Index : integer;procedure Print_Data_Out(Puppy : integer);begin

Writeln('This is the print routine',Puppy:5); Puppy := 12;

end;

And to call this procedure:

Print_Data_Out(Index);

{ since there is no var declaration for the parameter in the header of the procedure, the system makes a copy of Index, and passes the copy to the procedure which can do anything with it, using its new name, Puppy, but when control returns to the main program, the original value of Index is still there. }

22

Page 23: PASCAL

By reference:

var Index : integer;procedure Print_And_Modify(var Cat : integer);begin Writeln('This is the print and modify routine',Cat:5); Cat := 35;end;

And to call this procedure:

Print_And_Modify(Index);

{ The formal parameter name, Cat in the procedure, is actually another name for the actual variable named Index in the main program. A passed parameter with a var in front of it is therefore a two way situation. This is a "call by reference" since a reference to the original variable is passed to the procedure. }

23

Page 24: PASCAL

Formal and actual parameters The parameters listed within the

parentheses of the procedure header are called the formal parameters, whereas the parameters listed within the parentheses of the procedure call in the main program are referred to as the actual parameters.

24

Page 25: PASCAL

By reference or by value???

It may seem to you that it would be a good idea to simply put the word var in front of every formal parameter in every procedure header to gain maximum flexibility, but using all "call by references" could actually limit the flexibility. There are two reasons to use "call by value" variables when we can. The first is simply to protect some data from being corrupted by the procedure. This is becoming a very important topic in Software Engineering known as "information hiding" and is the primary basis behind Object Oriented Programming. Secondly is the ability to use a constant in the procedure call.

25

Page 26: PASCAL

Procedures can always call other procedures in their definitions. The silliest

example is calling the writeline procedure when defining some random procedure.

26

Page 27: PASCAL

Functions The major difference between a function and a procedure is

that the function returns a single value and is called from within a mathematical expression, a Writeln command, or anywhere that it is valid to use a variable, since it is really a variable itself.

A function begins with the reserved word function. Let’s consider the following function:

function Quad_Of_Sum(Number1,Number2 : integer) : integer;begin Quad_Of_Sum := 4*(Number1 + Number2);end;

{ there are two input variables inside the parenthesis pair being defined as integer variables, and following the parenthesis is a colon and another integer. The last integer is used to define the type of the variable being returned to the main program. }

27

Page 28: PASCAL

Recursion Recursion is also a technique allowed in Pascal. And

here is an example:

var Count : integer;

procedure Print_And_Decrement(Index : integer);begin

Writeln('The value of the index is ',Index:3); Index := Index - 1; if Index > 0 then Print_And_Decrement(Index); {recursive

part}end;

28

Page 29: PASCAL

Arrays The square braces are used in Pascal to denote a

subscript for an array variable. The array definition is standard, namely a variable name,

followed by a colon and the reserved word array, with the range of the array given in square brackets followed by another reserved word of and finally the type of variable for each element of the array.

To define an array, we do the following:

var Automobiles : array[1..12] of integer;

The variable Automobiles is defined as an integer variable but in addition, it is defined to have twelve different integer variables, namely Automobile[1], Automobile[2], Automobile[3], .. Automobile[12].

29

Page 30: PASCAL

var index : integer;

index := 1

Automobiles[Index] := Index + 10;

this is how we deal with the data stored in the array. In this case, the array automobiles at index 1 holds the value 11.

30

Page 31: PASCAL

DOUBLY INDEXED ARRAYS A doubly indexed array is defined as an array

from 1 to n, but instead of it being a simple data type, it is itself another array from 1 to m of type integer.the following code represents a doubly indexed array:It’s either:

var Checkerboard : array[1..8] of array[1..8] of integer;

Or: var Checkboard : array[1..8,1..8] of integer;

31

Page 32: PASCAL

The label declaration In the Pascal definition, a label is a

number from 0 to 9999 that is used to define a point in the program to which you wish to jump. All labels must be defined in the label definition part of the program before they can be used. Then a new reserved word goto is used to jump to that point in the program. Let us look at a demonstration in a program and it’s output in the next slides.

32

Page 33: PASCAL

label 274,Repeat_Loop,Help,Dog;

var Counter : byte; (* This limits us to a maximum of 255 *)

begin Writeln('Start here and go to "help"'); goto Help;

Dog: Writeln('Now go and end this silly program'); goto 274;

Repeat_Loop: for Counter := 1 to 4 do Writeln('In the repeat loop'); goto Dog;

Help: Writeln('This is the help section that does nothing'); goto Repeat_Loop;

274: Writeln('This is the end of this spaghetti code');end.

33

Page 34: PASCAL

The output will be as the following:

Start here and go to "help"This is the help section that does nothingIn the repeat loopIn the repeat loopIn the repeat loopIn the repeat loopNow go and end this silly programThis is the end of this spaghetti code

34

Page 35: PASCAL

strings According to the Pascal definition, a

string is simply an array of 2 of more elements of type char, and is contained in an array defined in a var declaration as a fixed length. the strings are defined as types in a type declaration even though they could have been completely defined in a var part of the declaration.the following code illustrates the way to define strings:

35

Page 36: PASCAL

type Long_String = array[1..25] of char; String10 = array[1..10] of char; String12 = array[1..12] of char;

var First_Name : String10; Last_Name : String12;

Full_Name : Long_String;

To assign a string to First_Name:

First_Name := 'John '; {6 spaces are must be added after the name John in order to complete the array chosen for First_Name which is String10 in this case.}

36

Page 37: PASCAL

Scalars

A scalar, also called an enumerated type, is a list of values which a variable of that type may assume. Look at the example below:

type Days = (Mon,Tue,Wed,Thu,Fri,Sat,Sun);

Time_Of_Day = (Morning,Afternoon,Evening,Night);

var Day : Days;

Time : Time_Of_Day;

37

Page 38: PASCAL

Sets Consider the following code:

type Goodies = (Ice_Cream,Whipped_Cream,Banana,Nuts,Cherry, Choc_Syrup,Strawberries,Caramel,Soda_Water, Salt,Pepper,Cone,Straw,Spoon,Stick);

Treat = set of Goodies;

var Sundae : Treat; Banana_Split : Treat; Soda : Treat;

A scalar variable is defined first, in this case the scalar type named Goodies. A set is then defined with the reserved words set of followed by a predefined scalar type. Several variables are defined as sets of Treat, after which they can individually be assigned portions of the entire set.

Then we can assign the variables to something from the goodies: Ice_Cream_Cone := [Ice_Cream,Cone];

Soda := [Straw,Soda_Water,Ice_Cream,Cherry];

38

Page 39: PASCAL

Records

We come to the grandaddy of all data structures in Pascal, the record. A record is composed of a number of variables, any of which can be of any predefined data type, including other records.

the next slide demonstrates how we can use Records.

39

Page 40: PASCAL

type Description = record Year : integer; Model : string[20]; Engine : string[8]; end;

var Truck : Description; Cars : array[1..10] of Description; Index : integer;

begin (* main program *)

Truck.Year := 1988; Truck.Model := 'Pickup'; Truck.Engine := 'Diesel';

In this example, the record Description holds a Year, a model and an Engine. To close this record, we must type the reserved word end followed by a semicolomn (end;)

We then created variables of type Description which is the recordTo modify a variable which is of type description, we have to state its

name.the name of the desired description to be modified. i.e. Truck.Year := 1988;

40

Page 41: PASCAL

Standard Input/Output We saw the example of the procedure Writeln as an

output Writeln('This is a standard output statement');

As for an input statement which will be used mostly in order to read from the keyboard, we use the Readln or Read procedures and we have to pass to them parameters which will be mainly variables. i.e. Var Number1,Number2,Number3 : integer;

Writeln(‘enter 3 numbers’); Read(Number1,Number2,Number3);

The parameter can be of any type. It depends on what is originally declared.

41

Page 42: PASCAL

File Input/Output Consider the following:

program Read_A_File;

var Turkey : text; Big_String : string[80];

begin (* main program *) Assign(Turkey,'READFILE.PAS'); Reset(Turkey); while not Eof(Turkey) do begin

Readln(Turkey,Big_String); Writeln(Big_String);

end; (* of while loop *) Close(Turkey);end. (* of program *)

The Assign statement assigns the input file to the variable Turkey in this exampleThe Reset(Turkey) statement, sets a pointer to the beginning of the fileOnce we did that, it is simple to read from that file just like we do from the keyboard.

42

Page 43: PASCAL

The EOF Function The Eof function is new and must therefore be

defined. When we read data from the file, we move closer and closer to the end of the file, until finally we reach the end and there is no more data to read. This is called "end of file" and is abbreviated Eof. Pascal has this function available as a part of the standard library which returns FALSE until we reach the last line of the file. When there is no more data to read left in the file, the function Eof returns TRUE. To use the function, we merely give it our file identifier as an argument. It should be clear to you that we will loop in this program until we read all of the data available in the input file.

see previous example

43

Page 44: PASCAL

The EOLN Function

The Eoln function is not used in this program but is a very useful function. If the input pointer is anywhere in the text file except at the end of a line, the Eoln returns FALSE, but at the end of a line, it returns a value of TRUE. This function can therefore be used to find the end of a line of text for variable length text input.

44

Page 45: PASCAL

Finally, we Close the file Turkey. It is not really necessary to close the file because the system will close it for us automatically at program termination, but it is a good habit to get into.

See the last shown example

45

Page 46: PASCAL

Encapsulation

Encapsulation is the cornerstone upon which object oriented programming is built, and without which it would not exist.

46

Page 47: PASCAL

InheritanceWhy do we use Inheritance? Once you have an object that is completely debugged and

working, it is possible that it can be reused on your next project. If you cannot use it exactly as is, but are required to make a change to it, you have two choices. You can modify the existing code and hope you don't introduce any analysis or coding errors, or you can inherit it into a new object and add code around the completely debugged object without actually modifying the original code. Several studies have shown that modifying existing code lead to a high probability of introducing errors into the modified code that are difficult to find because you are not as familiar with the code as you should be. Adding a few methods to an existing object, however, is not nearly as error prone and is the preferred method.

47