Pascal Language

download Pascal Language

of 12

Transcript of Pascal Language

  • 7/30/2019 Pascal Language

    1/12

    The Turbo Pascal Programming Languageby Steven Park

    for CSC415

    Turbo Pascal is a robust language, rich in data types and procedures. This makes it a very good

    teaching tool, especially for those who are just beginning in the world of programming. It makesthem appreciate why things are done a certain way in other languages

    HistoryThe field of Computer Science has not

    always been as it is today. Once the list ofavailable computer programming languages wassmall. Tools did not exist as they do today, toolsthat can be used to write simple programs. Toolsthat require very little knowledge of the languagethey are based on. Before this, programmersneeded to write the code. If the programmer didnot completely understand the programminglanguage or what they were programming, errorswould occur. Sometimes those errors could proveto be very costly, both in terms of finding the errorin the code, and in terms of output the codegenerated. It was imperative that programmerscompletely understand the language they wereprogramming in. This is where Pascal and TurboPascal first came into play.

    The Turbo Pascal programming languagewas developed as an extension to the Pascalprogramming language. The Turbo Pascalcompiler was written by Borland International and

    was intended to make the Pascal language an evenbetter language. At the time, Pascal was a verypopular language (Learn Pascal).

    The Pascal programming language camefrom the ALGOL programming language. It wasnamed after the 17th century mathematician, BlaisePascal (Learn Pascal). Mr. Pascal is credited withcreating the first mechanical digital computeraround the year 1640 (Computer History). ThePascal programming language began itsdevelopment in the 1960s, developed mainly byDr. Niklaus Wirth. The first programming outlineof the language was published in 1971 (Learn

    Pascal). In this report, Dr. Wirth described hisreasons for developing the language, highlightedby two main reasons:

    The development of the language Pascal isbased on two principal aims. The first is tomake available a language suitable to teachprogramming as a systematic disciplinebased on certain fundamental conceptsclearing and naturally reflected by the

    language. The second is to developimplementations of this language which areboth reliable and efficient on presentlyavailable computers. (Leestma 15).

    Dr. Wirth wanted a programming language thatcould teach people how to program effectively andefficiently with the computer systems of the 1970s.

    The Pascal language was very strongly

    typed, allowing its programmers to create theirown custom data types. This was a key reasonwhy Pascal was used as a teaching tool. It allowedprofessors to illustrate to students the importanceof programming structure and paying attention todata types. Because of the strong type casting,the language was very readable to its end-users andideal for beginning programmers (Learn Pascal).

    By the time the 1980s came about, Pascalwas a very popular programming language. Oneof the main reasons for its success was because ofits use in college placement tests. The Educational

    Testing Service, the company that creates andadministers college placement exams to highschool students, used Pascal as its language ofchoice on the exams. This caused many studentsto adopt Pascal as either a first language or afavorite language. Pascal remained the languageof choice for the ETS until 1999 when it wasreplaced by C++ (Learn Pascal).

    In 1983 Borland released its version of thePascal programming language named TurboPascal. The Turbo Pascal language was developedmainly by Anders Hejlsberg (Turbo Pascal). Themain advantage the Turbo Pascal offered over the

    ANSI standard Pascal was speed (Learn Pascal).The prefix Turbo came about because of theadded speed Turbo Pascal gave the end user uponcompilation (Turbo Pascal). Turbo Pascal madevery little changes to ANSI Pascal, but themodifications that were made drastically improvedthe compile speed. Turbo Pascal was able to readand compile source code at thousands of lines perminute, a harsh contrast to other compilers of thatera (Learn Pascal).

  • 7/30/2019 Pascal Language

    2/12

    Turbo Pascal brought new life into therealm of computer programming (Learn Pascal). Itfeatured an Integrated Development Environment(IDE) which was a relatively new idea in theprogramming market at the time (Turbo Pascal).An IDE is piece of computer software that allows

    the programmer to perform multiple tasks on theirsource code from within the same console. AnIDE usually consists of a text-editor for writing thesource code, a compiler or an interpreter to buildthe machine readable code from the source code, away to execute the code, and usually some type ofdebugger (Integrated Development Enviroment).The cost also was a reason for Turbo Pascal'spopularity. At the time of its introduction, TurboPascal could be bought for just under $50 in theUS (Turbo Pascal). The price, coupled with theextremely powerful and useful IDE, helped makeTurbo Pascal the standard programming language

    in the 1980s. Computer magazines and otherperiodicals usually released their sample sourcecode in Turbo Pascal (Learn Pascal).

    In the late 1980s Borland released TurboPascal version 5. This was a major step in thedevelopment of Turbo Pascal as it included ObjectOriented Programming instructions (Turbo Pascal).Object Oriented Programming gave languages theability to recognize and handle programmingobjects. Objects can be thought of as t hings ina program's source code. These things are separatebut can be brought together to perform a particularoperation (Object-oriented). Think of objects as

    Republicans and Democrats in Congress. Eachparty has their own views on particular agendas orideas. They usually discuss these amongthemselves. However, in order to get somethingaccomplished, the two sides must come togetherand pass laws. This is how objects work, comingtogether to perform a task and create a program.Object Oriented Programming generally makes aprogram easier to write, read, and maintain(Object-oriented).

    Turbo Pascal continued to make changesin the programming world. By version 7.0 it wasable to eclipse the MSDOS DOS Protected Mode

    Interface (DPMI) and allowed for memory usageover the DOS limit of 640k. When Windows 3.0was released, Borland released Turbo Pascal forWindows allowing programmers to developapplications for Windows (Learn Pascal). ButTurbo Pascal's downfall had already begun.

    As computers became more and more userfriendly and computer operating systems becamemore and more important, so did the languages that

    they were build around. Unix-like operatingsystems began to become popular and in 1991Linus Torvalds released his free Unix-likeoperating system called Linux. Linux became verypopular among young computer scientists bothbecause of its cost and the availability of its sourcecode (Linux). Unix and its brother Linux were

    both written from the C language. Becausestudents were learning Turbo Pascal to gainacceptance to colleges and then moving on tounderstanding the UNIX operating systems, theneed for Turbo Pascal slowly declined. Studentssaw no reason to learn both languages when Cwould do everything that was needed. To makematters worse, Microsoft soon released theWindows API allowing programmers to accessparts of the Windows code with their programs.The Windows API was released in C, and the usefor Turbo Pascal took a huge hit (Learn Pascal).

    Later in the 1990s, Borland droppedsupport for Turbo Pascal and began touting its newlanguage, Delphi. Delphi is based on many of thefeatures of Turbo Pascal. It is a Rapid ApplicationDevelopment environment, which allowsprogrammers to easily create programs in less timethan to write each line of the source code. One ofthe key components of the Delphi language is itsspeed, something it retained from Turbo Pascal(Learn Pascal).

    Despite the fact that Turbo Pascal is nolonger considered a popular language byprogramming professionals and programming

    enthusiasts, it is still a very useful language. Thefoundation that it was written on, making it auseful teaching language, can still hold true today.Any beginning programmer should considerlooking at Turbo Pascal, or one of its derivativessuch as ADA, as a useful starting point in theirunderstanding of programming languages.

    Data TypesTurbo Pascal, like Pascal, is based around

    four main data types. These include integer, real,char, and Boolean (Leestma 66). The integer andreal data types refer to numeric values. Integerrefer to counting numbers that do not have a

    decimal. They range from -32768 to 32767. Realdata types are more commonly referred to as floatsin other programming languages. Real numbersrepresent a much larger range of numbers and caninclude numbers with decimal points. In Pascalreal data types range from 3.4x10-38 to 3.4x1038.Real data types can be entered either as decimalnumbers or in scientific notation (Pascal Tutorial).If scientific notation is used, the symbol 'E' can beused to represent the separation of the mantissa or

    2

  • 7/30/2019 Pascal Language

    3/12

    whole number part and the exponent or power that10 is raised to.

    The char type in Pascal is used to store asingle character. The character must be enclosedin single quotation marks when it is assigned to avariable of type char. Only one character may be

    held in a variable of type char (Pascal Tutorial).The Boolean type is used to represent something aseither being TRUE or FALSE. Boolean data typeshave usefulness if you are dealing with logicalcircuits or any type of logical problem (Leestma66).

    In addition to these data types, TurboPascal also includes eight additional data types.These include shortint, longint, byte, word, single,double, extended, and comp (Leestma 66). Ashortint is a smaller integer that handles valuesbetween -128 and 127. A longint is an larger

    integer that can handle values ranging from-2147483648 to 2147483647. A byte is an integerthat holds values from 0 to 255. A word is similarto a byte except it goes from 0 to 65535. Single,doubles, extended, and comp are extensions to thereal data type. Single data types range from 1.5 x10-45 to 3.4 x 1038. Double data types refer to realnumbers between 5.0 x 10-324 and 1.7 x 10308.Extended data types go even further ranging from3.4 x 10-4932 to 1.1 x 104932. And finally, comp datatypes contain values between .5 x 10-45 and 1.1 x1038 (Turbo Pascal Tutorial).

    Turbo Pascal also introduced the string

    data type as an extension to the char data type(Leestma 66). The way Turbo Pascal deals withstrings is just as an array of characters. A stringtype can hold a maximium of 255 characters. Alimit can be defined when the string is declared byusing string[L], where L is the maximium

    number of characters that can exist in the string. Ifthe limit is left blank, then a maximium of 255characters is allotted for the string. Strings inTurbo Pascal use a unique method of determiningtheir length. The 0th position of the string, which isan array of characters, holds the character code forthe number of elements in the string (Leestma 509-510). For example a string that is 13 characters

    long would store a carriage return as the 0th

    element in the string. This is because a carriagereturn is represented by the ASCII code 13. Thisallows the string to look up its length whenoutputting the string and only displaying the first nelements in the character array. The first characterin a string is found in the 1st position of thecharacter array. Likewise, each individualcharacter in the string can be accessed like anyother array. However, if changes are made to the

    array after the nth character without changing the 0th

    element of the string, then the string will still thinkit is n characters long (Leestma 510-511).

    Another useful data type in Turbo Pascalis an array. An array differs from other data typesin that it is not really a specific data type. Instead,

    it is an in-line list of other specific data types.Arrays are denoted by first declaring an array type,known as an array declaration. Since this isconsidered defining a new type, this must be doneunder the TYPE heading. The array declarationlooks similar to:

    arraytype = ARRAY[]

    OF

    Where arraytype can be any valid identifier,

    range is specified to be any type of range and

    data type is a valid data type. In Turbo Pascal,

    range can be denoted by using the '..' keyword withthe lower and upper bounds on the left and rightside of it respectively (Leestma 448). Arrays canbe extremely useful when using any type of list.

    Expressions/Assignment StatementsIn Turbo Pascal to make an assignment, a

    programmer must use the assignment statement.The assignment statement looks like :=. On the

    left side of the assignment statement is a variable,which is represented by any valid Turbo Pascalidentifier. On the right side of the assignmentstatement is an expression. An expression canconsist of either a constant, another variable, or aformula which can be a combination of the othertwo (Leestma 81).

    Variables in Turbo Pascal are sometimesreferred to as identifiers. This is because of theirtrue nature as an identifying element. There is astrict set of rules that an identifier must hold trueto. An identifier can be of any length, however,only the first 63 characters will be recognized. Anidentifier can contain only letter, numbers, andunderscores. All other characters are invalid whennaming an identifier. It must also begin with eithera letter or an underscore and cannot begin with a

    number (Turbo Pascal Tutorial).

    Expressions in Turbo Pascal can be aconstant, or a variable, or a combination of thetwo. If you have any combination, you have whatis considered a formula. Turbo Pascal supports sixmain arithmetic operations. They are addition,subtraction, multiplication, real division, integerdivision, and modulus. The addition, subtraction,and multiplication work just like regular

    3

  • 7/30/2019 Pascal Language

    4/12

    mathematics and are denoted by their familiarsymbols of +, -, and * respectively. Real divisionworks very much the same way as regular divisiondoes. It will produce a real or floating pointnumber as a result of its operation and isrepresented by the / symbol. Integer divisionworks in much the same way as real division,

    except it only returns the integer part of thedivision. For example, 8 divided by 5 in realdivision is 1.6. However, if this operation isperformed with integer division the resultinganswer would be 1. Integer division is symbolizedby the keyword DIV. The modulus operation

    returns the remainder of the two numbers in integerdivision. In the previous example, the modulus of8 and 5 would be 3. The modulus operation isdenoted by the keyword MOD (Leestma 76).

    As in normal mathematical arithmetic, theorder of operation is always a concern. In Turbo

    Pascal multiplication, real division, integerdivision, and modulus have top priority followedby addition and subtraction. Each operation isperformed based on its priority level and ordinalposition of left to right (Leestma 77). So a leftmost multiplication would have priority over aright most real division.

    Other arithmetic functions that are builtinto Turbo Pascal include the transcendentalfunctions of sin, cos, tan, exponential and naturallog. The square root function is represented bysqrt(x), where x is either an integer or a real

    number. The round function, which rounds a real

    number to its nearest integer value, is representedby round(x). And a truncate function is

    represented by trunc(x), which drops the

    fractional part of a real number and returns aninteger number (Leestma 79).

    Assignments in Turbo Pascal must followsome rules. An expression must follow on theright-hand side of an assignment symbol. Youcannot perform multiple assignments on the sameline. It is legal for a programmer to assign aninteger value to a variable that is of type real. Thiscan be done without any typecasting and is one of

    the few instances that Turbo Pascal allows formixed-mode assignment. An integer variablecannot hold a real value, however. It is alsoimportant to note that the assignment symbol willbe used to replace the value of the left-handvariable. If the variable you are assigning theresult of an expression to already has a value, thenits value will be overwritten after the expressionhas been evaluated. It is also possible to assign avariable new content even if the expression

    contains the said variable. Because the right-handside is evaluated first, the value of the variable hasthe operation performed on it and then is replacedwith the result of the overall expression. One ofthe more common instances of this beingperformed is while incrementing a counter.Normally the counter would be incremented by

    usingcounter := counter + 1;

    The current value of counter is increased by oneand assigned to counter. The contents of a variableis left undefined, until it is explicitly assigned avalue (Leestma 83-86). You cannot perform anyarithmetic operations on a variable, unless it hasbeen assigned a value.

    Another method of incrementing is byusing step functions. Turbo Pascal includes twostep functions that are aptly named inc and dec.

    Both functions take two arguments, a variable and

    a step. The inc function takes the value of thevariable and increments it by the value stored inthe step argument. The variable must be an integervariable. So using the inc function is just like

    assigning the variable the result of itself added tostep. The dec function works in the same way,

    except instead of adding or incrementing, itdecrements a variable using subtraction. If the stepargument is not present, then a value of 1 isassumed and the variable is incremented ordecremented by 1 (Leestma 85-86).

    A Boolean function can be performed on aBoolean data type. The one Boolean function that

    is available in Turbo Pascal is the function odd(x).This function returns a true or a false depending onwhat the value of the integer x is. If the value heldin the variable x is odd, then the function returnstrue. If the value is even, the function returns false.Other Boolean operations that can be performed inTurbo Pascal, include less than, greater than, equalto, less than or equal to, greater than or equal to,and not equal to, represented by the symbols ,=, =, respectively (Leestma 124-125).These are commonly used in conditionalstatements to determine how one variable relates toanother variable. Each operation returns either a

    true or false depending on how the left-handed siderelates to the right-handed side.

    StructureIn order to develop a program in Turbo

    Pascal, one must follow certain design parametersthat refer to the structure of a Turbo Pascalprogram. This structure is the basis of how TurboPascal programs are written and read. In TurboPascal there are three distinct headings that must be

    4

  • 7/30/2019 Pascal Language

    5/12

    defined to properly identify a Turbo Pascalprogram. They are the Program heading,Declaration heading, and Statement heading(Leestma 103).

    The program heading is a relativelysimple heading and is actually optional in Turbo

    Pascal. The program heading consists of theprogram name, and any other files that the programmight use. The program heading should start witha heading of the form:

    PROGRAM name;

    Commonly, the name refers to the filename thatyou are working on, minus the file extension, butthis does not have to be the case. After thePROGRAM statement it is customary to provide

    some form of documentation about the program(Leestma 103). This is usually done with a

    comments section. Comments in Turbo Pascal canbe denoted by enclosing text in either { }'s or (*

    *)'s (Leestma 40). Comments can be placed

    throughout the program, but a short description isnice to have at the top of the program. Next in theprogram heading is the optional USES clause

    (Leestma 103). This is where you would list otherTurbo Pascal files that the program might use, suchas a graphics library (Leestma 67).

    The declaration heading is a much morerobust heading. It consists of five sub-headings.Each sub-heading is optional, and most of the timeall five are not used. They are the label section, the

    constant section, the type section, the variablesection, and the subprogram section (Leestma104).

    The label section is used to predefinelabels or parts of your program that execution canjump to. In the program, execution is usuallyjumped to one of these labels by using a GOTO

    statement such as GOTO . Labels are

    declared in the declaration heading by firstdeclaring the label heading, simply the wordLABEL followed by on the next line, a list of the

    labels. Valid labels include any positive integer or

    any valid identifier. Later in the program a linecan begin with label: where label is one of the

    predefined labels (Leesta 899-900).

    The constant sub-heading is used todeclare variables that are constant. Constantvariables are variables that do not change insidethe program (Leestma 67). The constant sub-heading is denoted by declaring the heading withthe word CONST followed by a new line. On the

    next line you can define all of your constants byusing the syntax:

    identifier = constant;

    where identifier is a valid Turbo Pascal identifierthat you want the constant to be identified as. Theterm constant refers to the value you want theidentifier to hold. Under the CONST heading you

    can have as many constants as you desire, but eachneeds to be on its own line (Leestma 104).

    The type sub-heading is where new datatypes are declared. It is also possible to rename atype and call it something else. The type sub-heading is defined by the keyword TYPE, followed

    by a new-line. On each subsequent line, types aredeclared by the syntax name = type, where

    name is any valid Turbo Pascal identifier and typeis any defined type in Turbo Pascal. Another use

    for declaring a type definition is to create anenumerated type. This is done in the TYPE sub-

    heading, and the syntax is much the same asdeclaring another type, except type is a list ofstrings or characters, separated by commas andenclosed in parenthesis (Leestma 418-420). Anenumerated type is sometimes easier to read laterin the program, since a variable declared as thistype can only hold the values listed in the type'sdeclaration. Another data entity that can bedeclared in the TYPE sub-heading, is a sub range.

    The syntax is again similar to that of other dataentities, except type is defined as first-

    value..last-value. The first-value and last-

    value represent the beginning and end of the subrange respectively. The one restraint on the first-value and last-value is that each must be a memberof an ordinal type (Leestma 431). An ordinal typeis any type whose members have value both behindthem and in front of them, except for the first andlast value. Integers are an example of ordinalvalues, as each integer, aside from the smallest andlargest, has both a number before itself and afteritself. Real or decimal numbers do not have thischaracteristic and are not consider ordinal types(Leestma 416).

    The variable sub-heading is defined in thedeclaration heading as the section to declarevariables and default values if desired. Thevariable sub-heading is denoted by the keywordVAR followed by a new-line. Each line defines a

    new variable of a new type, of the formvariable : type (Leestma 104). Where

    variable is any valid Turbo Pascal identifier andtype is any valid Turbo Pascal type or a typedefined under the TYPE sub-heading. The

    5

  • 7/30/2019 Pascal Language

    6/12

    identifier variable can also be a list of valid TurboPascal identifiers separated by commas and will allbe declared as the specified type (Leestma 73).

    Turbo Pascal supports subprograms ofboth procedures and functions (Leestma 174).They are usually defined after the VAR sub-

    heading in the declaration part of a program(Leestma 104). There is no keyword headingdenoting the beginning of the subprogram headingin the declaration section, instead each subprogramis denoted by the keyword PROCEDURE or

    FUNCTION depending on its type.

    The statement heading is where the bulkof the program begins. The statement section isdenoted by the keywords BEGIN and END.

    Enclosed between the BEGIN and END keywords

    are statements that are executed one at a time.Each statement is denoted to end with a semicolon.

    These statements contain the layout and overallprogram algorithm, needed to perform theprogram's task (Leestma 105). A statement can beany expression, procedure call, or control structureused to adequately perform a particular task.

    Control StructuresTurbo Pascal has three methods of control

    structures. Control structures are statements thatcontrol the flow of a program and the way theprogram runs (Introduction to Pascal). In TurboPascal, these control structures can be categorizedas either sequential, selective, or repetitive(Leestma 122). Each has its own characteristics

    and use.

    Sequential structure or statement structureis probably the most common structure element.As the name suggests, each statement is executedone after the other in order of occurrence.Sequential structure is denoted by the keywordsBEGIN and END. Enclosed in these keywords are

    statements separated by semicolons, each executedone after the other (Leestma 122-123). You maynotice that this is similar to the structure of thestatement heading of a Turbo Pascal program.This is because Turbo Pascal itself is a sequential

    programming language, because it reads one line ata time.

    The selective structure is a controlstructure that allows the program to skip todifferent alternative tasks, based on a condition.The common method of performing this is with anif statement (Leestma 135). There are severaldifferent variants of the if statement, includingIF-THEN, IF-THEN-ELSE, and IF-THEN-

    ELSE IF-THEN-ELSE. Each IF, THEN, ELSE,

    and ELSE IF are keywords in Turbo Pascal(Leestma 136, 138, 145). The syntax for an IF-

    THEN-ELSE IF-THEN-ELSE statement is as

    follows (Leestma 145):

    IF conditional THEN

    statements

    ELSE IF conditional THEN

    statements

    ELSE

    statements

    The conditional element usually represents aBoolean expression which represents a true orfalse. If the conditional is true, then the statementsunderneath it are executed. If more than onestatement is executed based on a conditional, thenthose statements need to be enclosed in a statementstructure, with a BEGIN and END (Leestma 136-

    137). There can be any number ofELSE IF-THEN sections. Once the criteria for the

    conditional has been met, either in the IF, ELSE

    IF, or ELSE section, execution of the program

    jumps to the end of the overall statement, after theELSE statements (Leestma 146-147). The syntax

    for IF-THEN or IF-THEN-ELSE is similar to

    that of the above. The only keyword that isrequired in an IF statement is the keywords IF

    and THEN, for a single condition. If only one

    statement is being executed based on theconditional, then the statement structure is notrequired. The Turbo Pascal compiler will

    recognize that there is only one statement andexecution will jump to the end as appropriate(Leestma 136-138).

    Another statement that can be used forselective purposes is the CASE statement. The

    case statement works in much the same way as aIF-THEN-ELSE IF-THEN statement. The

    syntax for a case statement is as follows:

    CASE selectorOFlabel_list : statement

    ELSE

    statementEND

    The selector in a case statement is usually avariable that will hold a value. If the value of theselector matches a value in the label_list,

    then the corresponding statement after the colon isexecuted. The label_list can be a list of

    possible values separated by commas, so if theselector matches any of those values, then the same

    6

  • 7/30/2019 Pascal Language

    7/12

    statement would be executed. Each possible valuethat needs to performs a distinct statement must beon a separate line after the CASE statement. If no

    value in any of the label_lists match that of

    the selector, then execution falls to the ELSE part,

    and the statement beneath it will be executed. TheELSE statement is not required, and if omitted and

    no value in the label_lists matches the

    selector, then execution drops to the next linefollowing the END statement. The END statement

    is required to denote the end of the CASE

    statement (Leestma 328-330).

    The repetitive structure is sometimesreferred to as the iterative structure or morecommonly as a loop structure. Turbo Pascalsupports three repetitive control structures -- theWHILE statement, the FOR statement, and the

    REPEAT-UNTIL statement (Leestma 150). One

    thing to look for in a loop is a continuous or

    infinite loop, a loop that never ends. If a programgets stuck in a continuous loop, then it will neverend.

    The WHILE structure is a looping

    structure that will iterate through a statement orseveral statements based on a conditional. Thesyntax of a WHILE statement is as follows:

    WHILE conditional DO

    statements

    The conditional is usually represented by some

    type of Boolean expression. The statements areexecuted while the conditional is true. If morethan one statement is being executed in the whileloop, then those statements need to be enclosed ina statement structure. Usually one of thestatements is a controlling element used to controlthe conditional (Leestma 150-152). If nocontrolling element is in the statements, then theconditional may always be true and a continuousloop may incur. Turbo Pascal version 7.0introduced the break statement, which can beused to break out of a loop. This provides a way toprevent an infinite loop (Leestma 934).

    Another repetitive structure is the FORloop. In a FOR loop, a statement or set of

    statements is executed within a specified range or anumber of iterations. The syntax for aFOR loop is

    generally:

    FOR control := initial_value

    TO final_value DO

    statements

    The control is a declared variable of any ordinaltype. The intial_value and final_value

    are of the same data type as control. Initially thecontrol is assigned the value of initial_value. With each loop the control

    variable is incremented by 1, until the value ofcontrol is equal to final_value. The

    statements are any valid Turbo Pascal statements,but if more than one statement is to be executed,then the statements need to enclosed is a statementstructure. The control variable cannot be modifiedwithin the FOR loop. Another variant of the FOR

    loop, is similar to the above syntax, except insteadof TO, the keyword DOWNTO is used. In this

    variant the control is assigned the initial value, butthe control variable is decremented by 1 with eachiteration of the loop (Leestma 335-339).Commonly a FOR loop is used to iterate through an

    array.

    Sometimes it is necessary to program aloop that centers around a post-test conditional. Apost-test conditional is a loop where theconditional is evaluated at the bottom of the loop.WHILE and FOR loops are both examples of pre-

    test conditionals, where the conditional isevaluated at the head of the loop. To accomplishthis in Turbo Pascal, you would use a REPEAT-

    UNTIL loop. The REPEAT-UNTIL loop is very

    similar to the WHILE loop, in that the conditional

    does not change by the looping structure. Instead,the conditional must be changed within the loop.

    The syntax for a REPEAT-UNTIL loop is asfollows:

    REPEAT

    statements

    UNTIL conditional

    As with the WHILE loop, the statements can be any

    valid Turbo Pascal statements and the conditionalusually represents a Boolean expression. The loopcontinues to repeat the statements until theconditional is false. The difference is that theconditional is not evaluated until the statementshave been executed at least one time. Unlike aWHILE loop, if more than one statement isrequired, they are each separated by semi-colonsbut do not have to be enclosed in a statementstructure (Leestma 341-343).

    Subprograms

    Sometimes it is necessary or easier to splita program up into smaller algorithms or tasks.Turbo Pascal allows you split a program into

    7

  • 7/30/2019 Pascal Language

    8/12

    smaller sections, called subprograms. The reasonfor using a subprogram is to localize a problem.This allows the programmer to easily debug theprogram if an error occurs, since the error wouldbe local to a specific subprogram. Subprogramsare declared and defined within the subprogramsub-heading of the declaration heading in a Turbo

    Pascal program. Turbo Pascal supports twodifferent types of subprograms, each with theirown characteristics, called procedures andfunctions (Leestma 174).

    A procedure in Turbo Pascal can belooked at as just a smaller program. A procedurecontains all the characteristics of a program butusually performs a specific task (Leestma 175).What defines a specific task is left up to theprogrammer's discretion. The syntax of aprocedure looks like:

    PROCEDURE name (parameters);

    The keyword PROCEDURE is used to signify the

    beginning of a procedure subprogram. The namecan be any valid Turbo Pascal identifier and is usedto reference the procedure later in the mainprogram. The parameters is an optional list ofparameter names which can be any valid TurboPascal identifier and its data type, each separatedby a semicolon. The line ends with a semicolonsignifying the end of the declaration (Leestma184).

    If parameters are specified then they must

    follow a specific syntax. The syntax of parametersin the parameter list is as follows:

    parameter : parameter_type

    data_type

    The parameter just refers to any valid Turbo Pascalidentifier. It can also be a list of parametersseparated by commas, but they each have the sameparameter_type and data_type. The

    data_type refers to the accepted data type of the

    value that the parameter or parameters can contain(Leestma 184). The parameter_type refers

    to a special meaning in Turbo Pascal. In someprocedures you will want a specific parameter tobe able to return a value back to the program orsubprogram that called it (Leestma 189). Eachparameter follows the same order as the parameterlist when the procedure is referenced, so that thefirst variable parameter in the reference refers tothe first parameter in the procedure heading. In theprogram or subprogram that references theprocedure, the matching variable in the reference

    will contain the value that the same parametervalue calculated in the subprogram. If that is thecase, you will need to specify that parameter as avariable, which is accomplished by using thekeyword VAR as the parameter_type. VAR is

    the only keyword that parameter_type will

    accept. If the parameter_type is empty, then

    the parameter is implied to be a value parameter.This means the parameter only brings values to theprocedure and does not take carry a value back tothe calling program or subprogram (Leestma 190-193).

    After the procedure name declaration, theprocedure follows the same general outline of aprogram. The name declaration is similar to theprogram heading which is called the procedureheading. Following the procedure heading is theprocedure declaration heading, which contains theexact same elements and sub-headings as the

    program sub-heading. After the declarationheading is the procedure statement heading, wherethe actual tasks and algorithms are performed forthat specific procedure. Again this follows thesame syntax as that of the program statementheading (Leestma 175).

    In the program the procedure can bereferenced by simply calling the procedure's namefollowed by a semicolon. If a parameter list isspecified in the subprogram heading, then thereference must contain a matching number ofparameters and of valid types as specified in theprocedure heading. When the program reads the

    procedure name, execution of the program jumpsto that specified procedure, and after the procedureis executed, the program returns to the nextstatement following the procedure call (Leestma186).

    The second type of subprogram availablein Turbo Pascal is a function (Leestma 175).Functions differ from procedures in that theyreturn a single value directly (Functions andScope). Just as in programs and procedures,functions follow the same structure with a heading,a declaration section, and a statement section. Thesyntax for a function heading is:

    FUNCTION name (parameters) :

    return_type;

    The keyword FUNCTION is used to signify that the

    subprogram is a function and will return a value oftype return_type. The parameters is a list

    of valid Turbo Pascal identifiers and their datatype, separated by a semicolon. Parameters followthe syntax of:

    8

  • 7/30/2019 Pascal Language

    9/12

    variable_name : type

    The variable_name refers to the name of the

    variable in the parameter list, and signifies how theparameter will be referenced inside the function.Following the function heading is the declarationsection and then the statement section (Leestma218-219).

    To return a value to the program orsubprogram from within the function, you assignthe name of the function the value to return. Thisis done somewhere within the statement section ofthe function by done using the assignment operator(Leestma 219).

    The main difference between a functionand a procedure is how values are returned. Aprocedure can return a value or more than onevalue, but it returns a value by variable in a

    parameter list (Leestma 191). A function returns avalue directly. When a function is called in aprogram, the value of that call becomes the valuethat the function returns (Leestma 217-219). Thisallows the programmer to add some level ofrecursion in the program, since a function canperform its task depending on the value of anothervalue returned by the same or another function. Asa general rule, procedures should be used whennone or more than one value is to be returned, anda function should be used when a single value is tobe returned (Functions and Scope).

    Object Oriented Programming

    With the release of Turbo Pascal version5.5, Borland introduced Object OrientedProgramming to the Turbo Pascal language (LearnPascal). Turbo Pascal's Object OrientedProgramming, or OOP, was a slight derivation ofthe Apple iteration of Object Pascal (Learn Pascal).OOP was important because it furthered the levelat which Turbo Pascal could operate at. By thistime other languages were being released andcould perform tasks better and faster than TurboPascal could. OOP was the next evolutionary step.

    The main concept behind OOP is theswitch from viewing the code as a set ofprocedures and operations, but instead as a list ofobjects or things. Objects can be viewed as anadvanced data type, but they do more. Objects arepart of an even bigger picture known as a class. Aclass contains all the objects and all the methodsthat can act upon those objects. A method issimilar to a procedure, but it only acts upon objectswithin the class. Another important definingcomponent of OOP is inheritance, or the ability to

    define subclasses that will inherit all of thedefining objects and methods in a superclass orparent. These subclasses are sometimes referred toas a child class, with the class it is derived frombeing called its parent class (Shammas 2-5).

    In Turbo Pascal, a class or object is

    defined in the type sub-heading of the declarationheading. It follows a similar syntax as defining anew data-type, but it has a few modifications:

    class_name=OBJECT(parent_class)

    fields

    method_headings

    END;

    The name refers to the name of the class and how avariable can be instantiated later in the program.The keyword OBJECT is used to signify that you

    are defining a class of objects. The

    parent_class refers to the name of the parentclass. This, along with the parenthesis, is notrequired if you are declaring a new class with noparent class. The fields refers to variables and

    data types that exist in the class and are defined inmuch the same way as variables are defined in thevariable sub-heading of the declaration heading.The method_headings is where you place

    headings to procedures or functions that act uponthe fields in the class called methods. Notice thatthese are simply headings and not actualsubprograms, although the heading is very similarto the subprogram name declaration. The actualfunction or procedure will be defined later, but thename must be noted. The keyword END followedby a semicolon signifies the end of the classdeclaration (Shammas 7-9).

    Later in the subprogram heading, you candefine the methods for the class by starting thedeclaration:

    PROCEDURE class_name.method;

    The class_name refers to the name of the class

    that contains the object you want to manipulate,and method refers to the name of the method

    declared in the class that you want to create. Thesyntax is the same if you want the subprogram toact as a function, simply replace PROCEDUREwith FUNCTION. Then you would write themethod just like you would any subprogram. Onevaluable piece of information you have is theability to access the fields that were defined in theclass declaration. You can think of the fields asglobal variables, as long as you are operating onthem within class methods (Shammas 9).

    9

  • 7/30/2019 Pascal Language

    10/12

    Inheritance also plays an important partwhen dealing with classes. A child class hasaccess to anything in the parent's class. TurboPascal supports single or linear inheritance or theability to only inherit from one parent. What thismeans is that you can define a subclass from a

    parent class and not have to repeat all the fieldsand objects in the subclass (Shammas 5). Thisallows a programmer to perform a more specifictask but not necessarily require that much morecoding.

    After all of this has been done, you nowhave a complete instance of an object. Whenreferencing this object in the main program, it canbe looked at more as a thing and not just as avariable, value, or statement. To create an instanceof this object, you would declare a variable to be ofthe stated class_name in the variable sub-

    heading of a program. Then in the programsource, you can access the specific methods of anobject by:

    variable.method

    Where variable refers to the variable that youdefined as the object type, and method is themethod to perform on that instance of the object,followed by any parameter list that may berequired. This is called sending a message to theobject. The message that is sent tells the object toperform the stated method on the specific variableinstance of that class (Shammas 10-11). It is

    important to note that any method called will onlyaffect the specific variable instance of the object.Each time a variable is declared to be of thatobject, the fields and methods of that object resetfor that specific variable.

    The inheritance part of a class is usuallyonly noticed in the actual method definition. Asstated earlier a subclass inherits all the fields andmethods of its parent class. A subclass can alsodefine new fields or methods, or even overridemethods or fields from the parent class. If this isdone, then those methods or fields becomecommon only to the subclass. In a specifiedmethod of the subclass you can access inheritedmethods by using the following syntax:

    parent_class.method

    Where parent_class is the name of the parent

    class and method is the inherited method from theparent class (Shammas 14-16). This can be usefulto allow the programmer to carry out a specific

    task without repeating the same steps.

    Abstract Data TypesAbstract data types are a collection of data

    and data types that are defined with specificoperations and relations among the collection.Abstract data types, or ADTs, are closely related toOOP, except each ADT is a type and not an object.Having ADTs allows the programmer to focus onthe structure of a program logically, rather thanthink about the actual implementation of a program(Leestma 650). This makes it very easy to portpart of a program to another program withouthaving to rewrite everything.

    A common part of ADTs is the recorddata structure. A record allows you to createsubtypes of various user-defined types. Thesesubtypes are known as fields. This allows you tocreate a data-type and store more specific

    information in variables of this data type. Forexample, a record data type might contain a stringfield and an integer field to represent someone'sname and age. The field types can actually beother record types, to give you even more specificinformation. Record data types are declared in thetype sub-heading and follow the syntax:

    variable = RECORD

    field-list

    END;

    Here, variable represents the name of the recordand field-list represents the field list. The

    field list is declared just as any other variable isdeclared. In the program to access specific field-list entries, use the notation:

    variable.field-list

    Where variable is the declared variable of the

    record type and field-list is the specific field

    list entry defined for that record (Leestma 596-600). Further, if one of the field list entries was ofanother record type, you would add an additional. after the field-list to weave through the

    layers.

    Exceptions/ConcurrencyAn exception is a way for a program to

    handle a specific run-time error. When programsare written, three types of errors must beconsidered. They are compile-time or syntaxerrors, run-time errors, and logical errors.Compile-time errors are easy to acknowledge,because the program will not compile if such anerror exists. Logical errors are difficult to find,

    10

  • 7/30/2019 Pascal Language

    11/12

    since they are mainly human errors such as usingan asterisk instead of a plus sign to add to numberstogether. The code will still run, but incorrectinformation will be gathered. Run-time errors fallsomewhere between the other two types of errors.A program will compile with a run-time error, butwhen executed, it will not finish (Leestma 47).

    Some programming languages allow youto handle these run-time errors through methodsknown as exceptions. Exceptions allows theprogrammer to redirect execution of a program toanother part whenever a particular run-time erroroccurs. This other part might contain contactinformation in order to contact the programmerand attempt to fix any bugs in the program. TurboPascal does not support this directly. Instead,Turbo Pascal has several built-in error messagesthat are written to the screen whenever a run-timeerror occurs. These error messages usually

    indicate the precise type of error and the linenumber in the code as to where the error wasdetected (Leestma 157). This allows theprogrammer to find the error or bug and fix theproblem accordingly.

    Concurrency is a method in computerprogramming languages of performing more thanone task at a time. A language that can supportconcurrency is able to execute two separateprocedures simultaneously or concurrently.Concurrency is a very advanced computerprogramming idea. Since Pascal was developedmainly for educational purposes, it did not support

    concurrency. Borland never got the chance to addconcurrency to the Turbo Pascal language, as thatproject was replaced with the Delphi series.

    EvaluationThe Turbo Pascal programming language

    never was designed to develop vast programs.Although it is better at this aspect than ANSI

    Pascal and other Pascal variants, it is still mainly ateaching tool used to teach programmers theimportance of key programming concepts. WhenBorland introduced Turbo Pascal it sold for a verysmall price, around $50 in 1984. This made it avery easy language to attain and learn, and alsomade it very popular. Turbo Pascal brought many

    changes to the Pascal language, including strings,screen control, and better memory management.One of the key features of Turbo Pascal is the IDEthat is shipped with it. With this IDE, TurboPascal was able to use syntax highlighting anderror highlighting, which greatly helps introductoryand advanced programmers (Turbo Pascal; the bestcost less). This increases productivity with thelanguage due to its greater writability.

    Turbo Pascal, like Pascal, was designed tobe very readable, thus its widespread usage as aneducational tool (Wade). It makes use of keywords

    that largely coincide with their English meaning.The specific type headings, which must beexplicitly declared, also help with the readability ofthe language. Turbo Pascal is very simple, becausea task can be performed in a logical manner(Sebesta 10). There are different methods toaccomplish a single task and several differenttechniques to write a specific algorithm, butgenerally these operations are performed in alimited number of ways, so as not to hinder theprogrammer's learning.

    The Turbo Pascal language has its place inthe programming language hierarchy. The idea

    was almost to view Turbo Pascal as an educationaltool. Borland and the makers of Turbo Pascalrealized this. They know there are other morepowerful languages to perform tasks. However,these tools become insufficient if the programmerdoes not understand how to utilize them. TurboPascal is an ideal language to teach beginningcomputer scientists the basis surrounding thesetools.

    11

  • 7/30/2019 Pascal Language

    12/12

    REFERENCES

    Computer History. Knobblycrab. 10 Nov. 2003 .

    Functions and Scope. University of Texas - Pan American. 10 Nov. 2003

    .

    Introduction to Pascal. 22 Aug. 1997. IICM. 10 Nov. 2003.

    Integrated Development Enviroment. 4 Nov. 2003. Wikipedia. 10 Nov. 2003.

    Learn Pascal. MIT. 10 Nov. 2003 .

    Leestma, Sanford and Larry Nyhoff. Turbo Pascal Programming and Problem Solving Second Edition.New York: MacMillan Publishing Company, 1993.

    Linux. 10 Nov. 2003. Wikipedia. 10 Nov. 2003 .

    Object-oriented programming. 7 Nov. 2003. Wikipedia. 10 Nov. 2003.

    Pascal Tutorial 1D. 2001. MIT. 10 Nov. 2003.

    Turbo Pascal. 9 Nov. 2003. Wikipedia. 10 Nov. 2003 .

    Turbo Pascal Tutorial. 10 Nov. 2003 .

    Turbo Pascal; the best costs less. July 1984. Creative Computing. 10 Nov. 2003.

    Sebesta, Robert. Concepts of Programming Languages Sixth Edition. Boston: Addison Wesley, 2004.

    Shammas, Namir. Object-Oriented Programming With Turbo Pascal. New York: John Wiley & Sons, Inc,1990.

    Wade, Michael. Pascal. Hiram College. Powerpoint slide..

    12