high-level programming languages - cldup.com · • programs are only applicable to a particular...

40
High-Level Programming Languages Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Upload: lamliem

Post on 24-Jun-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

High-Level ProgrammingLanguages

Nell Dale & John Lewis(adaptation by Michael

Goldwasser)

8-2

Low-Level Languages

• Programming in a low-level language is tedious! (have we made that clear yet?)

What are disadvantages of low-level languages?(e.g., machine code or assembly code)

• Programs are only applicable to a particular CPU.

• Only primitive data types are directly supported.

• Languages offer minimal expressiveness for describingcomplex behaviors

8-3

High-Level Languages

• Higher-level languages provide a richerset of instructions and support, makingthe programmer’s life even easier.

• Yet before a high-level program can beexecuted on a given CPU, it must betranslated back to machine code.

8-4

Advantages

Advantages of high-level languages include:

- better portability (program runs on many CPUs)

- richer data types and memory management

- natural structures for expressing flow of control

- much better support for software maintenance

- much better support for software reuse

8-5

Translation Process

A single high-level program can be translated tovarious CPU machine codes, but only if atranslator exists for each such machine.

• Compiler: translates an entire high-levellanguage program into machine code before it isexecuted.

• Interpreter: simulates a high-level languageprogram, translating commands to machinecode along the way, only as needed.

8-6

Compilers

Figure 8.1 Compilation process

8-7

A Compiled Language

Figure 8.2

8-8

An Interpreted Language

Figure 8.2

8-9

High-Level Languages

In designing high-level languages, goal is:• maximize expressiveness to aid programmers• yet ensure an automated translation process

Many, many different high-level languageshave been developed, e.g.:Fortran(1954), Lisp(1958), COBOL(1959), Simula(1964),Basic(1964), Smalltalk(1969), Prolog(1970), Pascal(1970),C(1971), ML(1973), Scheme(1975), Ada(1979),C++(1983), Perl(1987), Python(1991), Java(1995),C#(2000), VB.NET(2001)

8-10

Language Examples

Our text draws upon four high-levellanguages for the purpose ofdemonstration:

Ada, VB.NET, C++, Java

We will introduce and experiment with oneadditional language (not discussed in text):

Python

8-11

Variables

• Variables associate an identifying namewith a piece of data stored in memory.

Python

age = 25

SSCPU

LDI 25

STO age

age DAT

8-12

Data Types

• Some primitive data types may be handleddirectly by the CPU (e.g., numbers, boolean values)

• High-level Languages support additionaldata types, such as character strings, files,pictures, or other data types designed forparticular applications.

8-13

Data Types

• Many languages require an explicitdeclaration of the data type associatedwith a variable name. For example

int age;string greeting;

• In Python, the data type is determineddynamically.

age = 25 # stored as integergreeting = "Hello" # stored in ASCII

8-14

Assignment statement

the value of the right-hand expression isassociated with the left-hand variable

Python

age = 1 + age

SSCPU

LDI 1

ADD age

STO age

8-15

Arrays and Lists

Measurements

Might refer to a specificentry, for example as:

Measurements[6]

8-16

Output Commands

• Can evaluate and print any expression.

Python

print age

print "Hello", guest

SSCPU

LOD age

OUT

(no equivalency in SSCPU)

8-17

Input Commands

• In Python, a response can be read from the userusing the raw_input( ) command.

guest = raw_input("Who are you?")

• The variable is assigned to the string ofcharacters entered by the user. If thosecharacters are intended to represent a number,they must be explicitly converted.

age = int(raw_input("How old are you?"))

8-18

Boolean Expressions

• Boolean expression: a sequence of identifiers,separated by compatible operators, thatevaluates to True or False

• Boolean expression can be

– A Boolean variable

– An arithmetic expression followed by a relationaloperator followed by an arithmetic expression

– A Boolean expression followed by a Boolean operatorfollowed by a Boolean expression

8-19

Relational, Logical Operators

• sample Boolean expressions:xValue < yValuename == "Michael"(temp >= 75.0) and (day == "Tues" or month != "Oct")

not

or

and

Logical Operator

>=greater than or equal to>greater than<=less than or equal to<less than!=not equal to==equal toSymbolRelationship

8-20

Control Structures

• Control structure: an instruction thatdetermines the order in which other instructionsin a program are executed.

• These are implemented using the various "jump"commands in SSCPU.

• We will look at several common controlstructures: selection statements, loopingstatements, and subprogram statements

8-21

Selection Statements

• The if statement allows the program to test thestate of affairs using a Boolean expression

Python

if x < 0:x = -x

SSCPU

LOD xJNG workJMP rest

work LDI⇠♦ 0SUB xSTO x

rest …

8-22

If/Else Statements

Figure 8.3Flow ofcontrol ofif statement

8-23

Selection Statements

Python

if temperature > 70:rating = 5

else:rating = 2

SSCPU

LDI 70SUB temperatureJNG warmLDI 2JMP save

warm LDI 5save STO rating

8-24

Looping Statements

• The while statement is used to repeat acourse of action

while boolean expr :

loop body

rest of program

8-25

While Loop

High-Level Construct

while boolean expr :

loop body

rest of program

Low-Level Equivalency

top [evaluate expressionwith result in Acc]

JZR exit

[body]

JMP top

exit [rest of program]

8-26

While loop example

Python

total = 0val = int(raw_input( ))while val != 0:

total = total + valval = int(raw_input())

print total

SSCPU

LDI 0STO total

top INPJZR exitADD totalSTO totalJMP top

exit LOD totalOUT

8-27

While loop example

Python

count = 1while count <= 5:

print countcount = count + 1

SSCPU

LDI 1STO count

top LDI 5SUB countJNG exitLOD countOUTADD oneSTO countJMP top

exit …

8-28

Infinite loops, oops!

• What happens if the loop condition neverbecomes false?

8-29

Infinite loops, oops!

count = 1while count > 0:

print countcount = count + 1

8-30

Function Example

def greeting():print "Bonjour"

greeting()

8-31

Subprogram/Functions

• If the language does not already include aparticular behavior, we can define one!

• We give a section of code a name and usethat name as a statement in another partof the program

• When the name is encountered, theprocessing in the other part of the programhalts while the named code is executed

8-32

Subprogram Example

def Chorus():

Lucy in the sky with diamonds

Lucy in the sky with diamonds

Ahhh….

Picture yourself in a boat…

…And she’s gone

Chorus()

Follow her down to a bridge…

…and you’re gone

Chorus()

Picture yourself on a train…

8-33

Parameters

• There are times when the calling unitneeds to give information to thesubprogram to use in its processing

• A parameter list is a list of the identifierswith which the subprogram is to work.(usually placed in parentheses, often withdata type designations)

8-34

Parameter Example

Sing(name) Happy Birthday to you.

Happy Birthday to you.

Happy Birthday dear name

Happy Birthday to you.

My Birthday Celebration

Get Cake

Place Candles in Cake

Light Candles

Sing(“Michael”)

Blow out Candles.

8-35

Function Example

def greeting(person):print "Bonjour", person

greeting("Pierre")

8-36

Parameter Passing

• Value parameter: a parameter thatexpects a copy of its argument to bepassed by the calling unit

• Reference parameter: a parameter thatexpects the address of its argument to bepassed by the calling unit

• Analog to Machine Language: LDI vs LODimmediate operands vs. direct addressing

8-37

Machine Code Implementation

• The body of a function is code that can bestored somewhere in memory.

• A function call is enacted through the useof a JMP command.

• When the function completes, it must jumpback to the context at which it was called.Technically, this requires a form of "jump"with an indirect operand (not supported bySSCPU)

8-38

Nested Subprograms

Subprogram B( )

Call C( )

Subprogram A( )

Call B( )

Subprogram C( )

8-39

Recursion

• Recursion: the ability of a subprogram to callitself

• Each recursive solution has at least two cases– base case: the one to which we have an answer– general case: expresses the solution in terms of a call

to itself with a smaller version of the problem

• For example, the factorial of a number is definedas the number times the product of all thenumbers between itself and 0:

N! = N * (N − 1)!

8-40

Recursion

def factorial(n):if n <= 0:

return 1else:

return n * factorial(n-1)