Programming Languages and Design Concept

35
Programming Languages and Design Concept Languages Evaluation Assignment 1 Evaluation and Analysis of ALGOL, PASCAL and ADA Programming Languages

Transcript of Programming Languages and Design Concept

Programming Languages and DesignConcept

Languages Evaluation Assignment 1

Evaluation and Analysis of ALGOL,PASCAL and ADA Programming

Languages

Evaluation and Analysis of ALGOL, PASCAL & ADA Programming Languages

Summary

In this report my main goal is to present a more informativediscussion about three important programming languages. Thesethree languages are ALGOL, PASCAL & ADA. Through this reportI’m going to evaluate and analyze these languages by comparingtheir strengths, weaknesses, features such as programstructure, variable declaration, data types, data structures,controls structures, parameter passing mechanisms etc. andmajor contribution to modern languages.

ii

Table of Content

1. Summaryii

2. Introduction1

3. Major contributions to modern languages2

4. Features -- ALGOL--

4.1 Program structure34.2 Variable declaration44.3 Data types and structures54.4 Control structures64.5 Parameter passing mechanisms7

5. Features – PASCAL--

5.1 Program structure9

5.2 Variable declaration10

iii

5.3 Data types and structures115.4 Control structures125.5 Parameter passing mechanisms13

6. Features –ADA--

6.1 Program structure14

6.2 Variable declaration156.3 Data types and structures166.4 Control structures176.5 Parameter passing mechanisms18

7. Strengths and Weaknesses7.1 Algol197.2 Pascal207.3 Ada21

8. Conclusion22

9. References23

iv

v

Introduction

Algol In the mid1950s it became apparent to many scientists that auniversal, machine independent programming language would bevaluable. Therefore Algol 58 was developed which greatlyinfluenced many other languages. In the sense that most modernlanguages are "algol-like", it was possibly the mostsuccessful of the four high-level programming languages withwhich it was compared to (FORTRAN, Lisp, and COBOL). Moreover,it was the first programming language which gave seriousattention to formal language definition and through the ALGOL-60 Report introduced Backus-Naur Form, a principal notationfor language design. The ALGOL-60 was a very simple and clearlanguage.Niklaus Wirth based his own ALGOL W on ALGOL 60 beforedeveloping Pascal. [3]

Pascal

Pascal is a historically influential imperative and proceduralprogramming language, designed and published around 1970 byNiklaus Wirth as a small and efficient language intended toencourage good programming practices using structuredprogramming and data structuring.

It has evolved significantly since that day, with a lot ofcontributions by the various compiler constructors (Notably:Borland). PASCAL is a programming language named after the17th century mathematician Blaise Pascal. Pascal provides ateaching language that highlights concepts common to allcomputer languages. It also standardizes the language in sucha way that it makes programs easy to write. Strict rules makeit difficult for the programmer to write bad code.

Pascal introduced concepts and mechanisms which enabledprogrammers to define their own structured data types, andalso made it easier to build dynamic and recursive datastructures such as lists, trees and graphs. Important featuresincluded for this were records, enumerations, subranges,dynamically allocated variables with associated pointers, andsets. To make this possible and meaningful, Pascal has a

1

strong typing on all objects, which means that one type ofdata cannot be converted or interpreted as another withoutexplicit conversions. [2]

Ada

Ada is a high-level Pascal descended language whosedevelopment was initiated in 1975 by the Department ofDefense. Ada was intended to be a common language that couldbe used on the department's computers, which were produced bymany different manufacturers. The first version of thelanguage specification was completed in 1979. Ada was namedafter Ada Lovelace (1815–1852), who is credited as being thefirst computer programmer, Ada is similar to Pascal but Adahas not been widely spread in programs other than those of theDepartment of Defense screaming to get out from inside itsvast, elephantine bulk. It has built-in language support forexplicit concurrency, offering tasks, synchronous messagepassing, protected objects, and non-determinism. [1]

Major contributions to modern languages

Algol

Algol is one of the major milestones in programming languagedevelopment. This is partly reflected in the terms it added tothe programming language vocabulary, which includes type,formed parameter, actual parameter, and block call by value,call by name, scope, dynamic analysis and global and localvariables.Eventually almost all the programming languages became "Algol-like" that is, block-structured, nested, recursive, and freeform.One of the major contributions of ALGOL-60 was that it used ahierarchical structure throughout its design.

Pascal

2

This contains many additional features that are convenient forthe development of large-scale programs. Pascal is influentialon software development because of its wide use as a "learninglanguage." Aspects of Pascal are also seen in other languages.For example, the Oracle database procedural programminglanguage PL/SQL has always felt eerily similar to Pascal. Onemight argue that Pascal's influence is felt more todayindirectly via languages such as PL/SQL than via direct use.Mostly Pascal offers numerous advantages as a "learninglanguage." Ada is also a language that’s been inspired orinfluenced by Pascal.

Ada

Ada has advanced programming facilities which are notavailable in modern languages as well. But also features foundin existing programming languages such as PASCAL, Algol 60,and Fortran are there as well. Ada supports new and changingtechnologies, facilitates development of complex programs andhelps make code readable and portable. Ada is used throughouta number of major industries to design software that protectsbusinesses and lives.

Features

3

Algol

1.Program structure

Algol programs are hierarchically structured.One of the primary characteristics and important contributionsof Algol is its use of Hierarchical structure, or nesting,throughout its design.An Algol program is composed of number of nested environments;

begin integer N; Read int (N); begin real array Data [1:N]; real sum, avg; integer i; sum i = 0; for i = 1 step 1 until N do begin real val; Read Real (val); Data [i] := if val < 0 then -val else val; end; for i := 1 step 1 until N do sum := sum + Data[i]; avg := sum/N; Print Real (avg) endend

4

2.Variable declaration

Variables are declared as TYPE var, var, var; Where TYPE is INTEGER, REAL, ARRAY, STRING. Another typeallowed is called a SWITCH declaration. This allows you todefine a range of values to be stored in a variable, where thevalues are actually labels (as used in GOTO statements). Thiswas used similarly to a switch or case statement in laterlanguages but was far more primitive and was replaced by atrue CASE statement in ALGOL 68. ALGOL 68 also introduced theUNION to the ALGOL languages.

Arrays are declared with both the reserved word array and[range] notation. If no type is provided, arrays default toREAL. The range allows you to specify the starting and endingindices for the array. Thus, arrays are not limited to0..num-1 as in C, or 1..num as in FORTRAN. Instead, you mightspecify [0:99] or [1:100] or [-50:49]. Arrays with commonsizes can be declared with a single range as follows:

INTEGER ARRAY A, B, C[5:10];

Local variables are generally called local variables in ALGOL68. Variables must be declared before use. In traditionalALGOL 68, variables must be declared before any labels: in acompound-clause.

The declaration of a variable, without assigning a value takesthe form: <typename> <variablename>; Ex: int j;

It is possible to initialize variables with expressions havingknown values when they are defined.

5

The syntax follows the form: <typename> <variablename> :=<initializing expression>;

Ex: SHORT INT b1 := 2500;

3.Data types and structures

There are three main data types in Algol: integer, real andstring.

Data structures

Primitive scalars: integer, real, boolean

Constructor: array

Array bounds and dimensions are unconstrained. (the Zero-One-Infinity Principle.) Ex:

integer array aMatrix[-10:10, 0:20];

Arrays are dynamic: space is allocated at block entry timeand fixed until block exit. Ex:

6

begin integer array aList[lowest:highest]; . . . end

E.g.,

begin integer i; procedure f(x); real x; x := 0; integer array days[ 0: i ]; begin . . . end begin i := 7; f(x); . . . i := 30; f(x); . . . end end

4.Control structures

All other Algol imperatives alter the flow of control in theprogram. The most obvious of these is the goto statement,which transfers to a labeled statement. Algol has aconditional statement, the if-then-else and an iterativestatement, the for-loop which is an elaboration of Fortran’sDo loop.

Some of the control structures in Algol are:

7

goto if-then-else for loop switch

GOTO: like Fortran's, except for scope rules for labels (can only go to a label at the same lexical level, or an enclosing lexical level)

if-then-else: both statement and expression forms

y := if x=3 then 5 else 6;

for loop: definite, indefinite iterations. In general, a for-loop generates a sequence of values to be assigned successively to the controlled variable.

For loop have a number of variants:

for i := 1 step 2 until N do a[i] := b[i];

for newGuess := Improve( oldGuess ) while abs( newGuess - oldGuess ) > 0.0001 do oldGuess := newGuess;

for days := 31, if mod( year, 4 ) = 0 then 29 else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 do . . .

for i := 3, 7, 11 step 1 until 16, i ÷ 2 while i >= 1, 2 step i until 32 do print( i );

switch statement: supports a kind of computed goto; now obsolete (case statement is better)

8

5.Parameter passing mechanisms

The two best known parameter passing methods are pass by value(call-by-value) and pass by reference (call-by-reference).

Pass by value (call-by-value):

The default parameter passing method was pass by value, which,like in C, means that parameter values are copied into theformal parameters from which point the formal parameters actlike local variables.

Pass by name:

Is powerful, Can be confusing and Expensive to Implement.

However, ALGOL also introduced pass by name which gave theprogrammer the ability to change a formal parameter's valueand thus affect the actual parameter.

The way this worked is through a thunk -- a parameterlessfunction which would perform a textual substitution of theformal parameter name with that of the actual parameter. Soin effect, pass by name is merely a form of substitution thatthen has the program access non-local variables. This isconfusing and dangerous and while it can lead to someinteresting code, it is far more dangerous than pass byreference or pass by result.

Here is the original code before the thunk executes:

begin integer idx; // variable available in the main code real procedure sum (i, lo, hi, term); //function, i and term passed by name value lo, hi; // function declarations

9

integer i, lo, hi; real term; begin // begin of sum function real temp; temp := 0; for i := lo step 1 until hi do temp := temp + term; sum := temp end; print (sum (idx, 1, 100, 1/idx)) // main code contains function callend

The above code becomes the following:

begin integer idx; real sum; begin // pass by name unfolds the code so that real temp; // hi becomes 100, lo becomes 1 and term temp := 0; // becomes idx for idx := 1 step 1 until 100 do temp := temp + 1/idx; sum := temp end; print (sum)end

Pass by reference:

Reference to the actual parameter is copied into the formal parameter.

Pass by result:

10

In pass by result formal parameter acts as an un-initialized local variable which is given a value during the execution of the procedure.On leaving the procedure, the value of the formal parameter isassigned to the actual parameter which must be a variable.

Pascal

1.Program structure

A Pascal program basically consists of the following parts:

Program name Uses command Type declarations Constant declarations Variables declarations Functions declarations

11

Procedures declarations Main program block Statements and Expressions within each block Comments

Following format shows the basic syntax for a Pascal program:

program {name of the program}uses {comma delimited names of libraries you use}const {global constant declaration block}var {global variable declaration block}

function {function declarations, if any}{ local variables }begin...end;

procedure { procedure declarations, if any}{ local variables }begin...end;

begin { main program block starts}...end. { the end of main program block }

2.Variable declaration

All variables must be declared before we use them in Pascalprogram. All variable declarations are followed by the var

12

keyword. A declaration specifies a list of variables, followedby a colon (:) and the type.

Syntax of variable declaration is:

varvariable_list : type;

Here this type must be a valid data type such as character,integer, real, boolean, or any user-defined data type andvariable_list should consist of one or more identifiersseparated by commas.

Some valid variable declarations are:

age, weekdays : integer;initials, grade: char;name, surname : string;

13

3.Data types

Type Description

Character Typically a single octet (one byte). This is aninteger type.

Integer The most natural size of integerfor the machine.

Real A single-precision floating point value. Boolean Specifies true or false logical values. This is

also an integer type. Enumerated Specifies a user-defined list. Subrange Represents variables, whose values lie within a

range. String Stores an array of characters.

14

4.Controls structures

Programming languages provide various control structures thatallow for more complicated execution paths.

A loop statement allows us to execute a statement or group ofstatements multiple times and following is the general form ofa loop statement in most of the programming languages:

15

Pascal programming language provides the following types ofloop constructs to handle looping requirements.

Loop Types

while-do loop Repeats a statement or group ofstatements while a given condition is true. It teststhe condition before executing the loop body.

for-do loop Executes a sequence of statementsmultiple times and abbreviates the code that manages the

loop variable. It allows only +/- 1 increments in the loop variable

repeat-until loop Like a while statement, except thatit tests the condition at the end of the loop body.

nested loops You can use one or more loopinside any another while, for or repeat until loop.

5.Parameter passing mechanisms

There are two ways to pass information which are call by value(pass-by-value) and call by reference (pass-by-reference).

The call by value method of passing arguments to a subprogramcopies the actual value of an argument into the formalparameter of the subprogram. In this case, changes made to theparameter inside the function have no effect on the argument.

16

Call by value:

This method copies the actual value of an argument into theformal parameter of the subprogram. In this case, changes madeto the parameter inside the subprogram have no effect on theargument.By default, Pascal uses call by value to pass arguments. Ingeneral, this means that code within a subprogram cannot alterthe arguments used to call the subprogram.

Call by reference:

This method copies the address of an argument into the formalparameter. Inside the subprogram, the address is used toaccess the actual argument used in the call. This means thatchanges made to the parameter affect the argument.In order to pass the arguments by reference, Pascal allows todefine variable parameters. This is done by preceding theformal parameters by the keyword var.

For example

procedure swap( var a: integer, var b: integer )var t;begin t := a; a := b; b := tend

Where the var formal parameters a and b are passed by reference( var t declares a local variable).

17

Ada

1.Program structure

ADA syntax is similar to PascalADA uses a keywords convention to improve readabilityADA has four categories of constructs:

declarations expressions statements types

The type system in ADA is stronger as it consistently usesname equivalence.

Simple Ada program:

with Ada.Text_IO; use Ada.Text_IO;procedure Hello isbegin Put_Line ("Hello, world!");end Hello;

The two most important facilities provided byADA:

the package the task

The package and the task support information hiding Packages can be used as libraries, shared data areas (data structures but no procedures), data structure managers.

18

2.Variable declaration

Before using a variable, have to declare it. To do this hasvarious options. To declare a variable, in the line underprocedure, use the following formula:

VariableName : DataType;

The declaration starts with the name of the variable:

The name of a variable must be in one word It must start with a letter It can include a combination of letters, digits, and

underscores It must not contain special characters

The above formula is used to declare one variable. You can useit to declare various variables, each on its own line. Thiswould be:

VariableName1, VariableName2 : DataType1;

If declaring more than one variable but those variables usesthe same data type, declare them on the same line, separatingtheir names wit commas. This would be done as follows:

VariableName1 : DataType1;VariableName2 : DataType1;

abort abs abstract accept accessaliased all and array atbegin body case constant declaredelay delta digits do elseelsif end entry exception exit

19

for function generic goto ifin interface is limited loopmod new null not ofor others out overriding package

pragma private procedure protected raiserange record rem renames requeuereturn reverse select eparate subtype

synchronized tagged task terminate thentype until use when while

with xor

Ada uses some words that you must not use to name thevariables. These are referred to as reserved words. They are:

3.Data types

Ada's type system is not based on a set of predefinedprimitive types but allows users to declare their own types.This declaration in turn is not based on the internalrepresentation of the type but on describing the goal whichshould be achieved. This allows the compiler to determine asuitable memory size for the type, and to check for violationsof the type definition at compile time and run time.

Ada supports numerical types defined by a range, modulo types,aggregate types (records and arrays), and enumeration types.Access types define a reference to an instance of a specifiedtype; untyped pointers are not permitted. Special typesprovided by the language are task types and protected types.

For example a date might be represented as:

type Day_type is range 1 .. 31;type Month_type is range 1 .. 12;type Year_type is range 1800 .. 2100;type Hours is mod 24;

20

type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); type Date is record Day : Day_type; Month : Month_type; Year : Year_type; end record

Types can have modifiers such as limited, abstract, privateetc. Private types can only be accessed and limited types canonly be modified or copied within the scope of the packagethat defines them.

4.Controls structures

Ada is a structured programming language, meaning that theflow of control is structured into standard statements. Allstandard constructs and deep level early exit are supported sothe use of the also supported 'go to' commands is rarelyneeded.

Example of a use of the control structure in Ada:

-- while a is not equal to b, loop.

21

while a /= b loop Ada.Text_IO.Put_Line ("Waiting");end loop; if a > b then Ada.Text_IO.Put_Line ("Condition met");else Ada.Text_IO.Put_Line ("Condition not met");end if; for i in 1 .. 10 loop Ada.Text_IO.Put ("Iteration: "); Ada.Text_IO.Put (i); Ada.Text_IO.Put_Line;end loop; loop a := a + 1; exit when a = 10;end loop; case i is when 0 => Ada.Text_IO.Put ("zero"); when 1 => Ada.Text_IO.Put ("one"); when 2 => Ada.Text_IO.Put ("two"); -- case statements have to cover all possible cases: when others => Ada.Text_IO.Put ("none of the above"); end case; for aWeekday in Weekday'Range loop -- loop over an enumeration Put_Line ( Weekday'Image(aWeekday) ); -- output string representation of an enumeration if aWeekday in Working_Day then -- check of a subtype of an enumeration Put_Line ( " to work for " & Working_Hours'Image (Work_Load(aWeekday)) ); -- access into a lookup table end if;end loop;

22

5.Parameter passing mechanisms

Ada uses different designations: IN, OUT, IN OUT.

For scalar data types (such as integers), IN is the same ascall by value, OUT is the same as call by result, and IN OUTis the same as call by value result. In addition, INparameters are local constants therefore can't assign intothem.For compound data types such as arrays, these can beimplemented as above, or using call by reference.

For example

procedure shift(a:out integer, b:in out integer, c:in integer) isbegina := b; b := c;end shift;

Where a is passed out, b is passed in and out, and c is passedin.

in mode parameters can be read but not written in thesubroutine. This is the default when no mode is given. Theactual parameter is an expression.

out mode parameters can be written but not read in thesubroutine. The formal parameter can be read and written. (InAda 83 out parameters were write-only.)

in out mode parameters can be read and written in thesubroutine. The actual parameter goes into the call and may beredefined. The formal parameter is a variable.

23

Strengths and Weaknesses

Algol

Strengths

ALGOL 58 introduced the concept of data type, although onlyvariables that were not floating-point required explicitdeclaration. It added the idea of compound statements, whichmost subsequent languages incorporated.

In Algol 60 the concept of block structure was introduced.This allowed the programmer to localize parts of programs byintroducing new data environments, or scopes.

Every imperative programming language designed since 1960 owessomething to ALGOL 60. It was the first language that wasdesigned to be machine independent. It was also the firstlanguage whose syntax was formally described. This successfuluse of the BNF formalism started several important fields ofcomputer science: formal languages, parsing theory, and BNF-based compiler design.

Finally, the structure of ALGOL 60 affected machinearchitecture.

Weaknesses

24

For one thing, some of the features of ALGOL 60 turned out tobe too flexible; they made understanding difficult andimplementation inefficient. The best example of this is thepass-by-name method of passing parameters to subprograms.

The lack of input and output statements in the language wasanother major reason for its lack of acceptance.Implementation-dependent input/output made programs difficultto port to other computers.

Pascal

Strengths

The basic elements have been kept through the years:

Easy syntax, rather verbose, yet easy to read. Ideal for teaching.(Readability)

Strongly typed. Procedural. Case insensitive. Allows nested procedures. Easy input/output routines built-in.

25

Well structured Supports OOP (Object Oriented Programming)

Weaknesses

Reduced popularity

Finding people for software projects who alreadyhave experience in Pascal could be difficult. It could beharder to find suitable library solutions for specificproblems.

More usage of reserved words than reserved characters

Sometimes writing all the reserved words (like"begin", "end", "then",...) feels uncomfortable. Otherlanguages just use parentheses or curly braces – that is oneletter. Editor functions like "match-correspondingparentheses/brace" or in Pascal-context "match correspondingbegin/end" are harder to find.

Pascal was devised as a teaching language a few years before C but was very limited with poor string and file handling

Ada

26

Strengths

Ada is a carefully designed, general-purpose programminglanguage. Ada is the first internationally standardized objectoriented programming (OOP) language.

Ada encourages good programming practices by incorporatingsoftware engineering principles with strong typing,modularity, portability, reusability and readability. Thesefeatures reduce costs in software development, verifying,debugging, and maintenance that typically puts strain on anorganization's resources over the life of the software.

Flexibility Avoidance of “Namespace Pollution” Data Abstraction and Information Hiding Methodology neutrality Real-time support Safety-critical support Ada uses compiler checking effectively;[4]

To eliminate many common errors that cause painful, time-consuming debugging efforts that characterize and slow downmany software development projects. Various language features,such as strong typing and separate (but not independent)compilation, make this checking process possible. Otherfeatures, such as the way pointers (called access values) areused, also contribute to the avoidance of many typicaldifficulties

Ada has built-in support for concurrency and distribution.

Ada has built-in constructs called tasks, protected objects, andpartitions that provide elegant support for capabilities thatare becoming increasingly vital for modern systems. Ada alsohas low-level representation clauses, which are valuable wheninterfacing to physical devices or communicating acrossnetworks.

Weaknesses

27

Ada is not appropriate for writing some concurrentprograms like concurrent versions of divide and conqueralgorithm.

Hard to write parallel numerical computations. Tasks can’t determine their identities which prevents

easy expression of certain types of paradigms. Task types can’t be parameterized. Buffer, register and interrupt address can’t be specified

dynamically. Entry families cannot be associated with a set of

interrupts & doesn’t give programmer sufficient controlover the task scheduling algorithm.

Conclusion

Although Ada is based upon Pascal, it is quite a differenttype of language. Pascal is excellent as an educational toolbut is inappropriate for major commercial or real-timeprojects. Ada is more complex than Pascal but has a capabilityfor large systems. Ada has a set of unique technical featuresthat make it highly effective for use in large, complex andsafety-critical projects.

Algol was used mostly by research computer scientists in theUnited States and in Europe. Its use in commercialapplications was hindered by the absence of standardinput/output facilities in its description.

Although in Algol there were many other problems, theentrenchment of Fortran among users and the lack of support byIBM were probably the most important factors in ALGOL 60’sfailure to gain widespread use.

The choice of a language for a project is very important.Currently both languages are restricted to long-term projectsbecause of the absence of production quality compilers andthere are more advance languages available now.

28

References

[1] Wikipedia – http://en.wikipedia.org/wiki/Ada_%28programming_language%29[2] Wikipedia-http ://en.wikipedia.org/wiki/Pascal_ %28programming_language%29[3] Wikipedia –“http://en.wikipedia.org/wiki/ALGOL”[4] Website –“http://www.adacore.com/adaanswers/benefits-and-features”[5] Book- “Principles of programming languages by B.J.MacLennan”[6] Book- “Concepts of programming languages by Robert W.Sebesta”

29

30