0% found this document useful (0 votes)
6 views

Lect6_PLangs

Chapter 6 discusses the evolution and concepts of programming languages, starting from machine language to high-level languages and various programming paradigms such as imperative, declarative, functional, and object-oriented programming. It highlights the transition from low-level programming to more abstract forms that allow developers to focus on problem-solving rather than machine-specific details. The chapter also covers traditional programming concepts, including language statements and the structure of imperative programs.

Uploaded by

hesap1epic
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lect6_PLangs

Chapter 6 discusses the evolution and concepts of programming languages, starting from machine language to high-level languages and various programming paradigms such as imperative, declarative, functional, and object-oriented programming. It highlights the transition from low-level programming to more abstract forms that allow developers to focus on problem-solving rather than machine-specific details. The chapter also covers traditional programming concepts, including language statements and the structure of imperative programs.

Uploaded by

hesap1epic
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 54

Chapter 6: Programming Languages

• 6.1 History
• 6.2 Traditional Programming Concepts
• 6.3 Procedural Units
• 6.4 Language Implementation
Programming Languages

• Allow humans to:


– avoid having to deal with the low-level details of
machine-language programming
– concentrate on the problem being solved
Historical Perspective (1)
“1st Generation”
• In the beginning there was:
– Machine Language:
156C 166D 5056 306E C000

Sequences of instructions are encoded as numeric digits


e.g. “Move the contents of register 5 to register 6”
could be expressed as 4056
Writing programs in such a language is tedious and error-prone
By the 1940s notational systems were being introduced by which
instructions could be represented in mnemonic form
e.g. The above instruction could become MOV R5 R6
Historical Perspective (2)
• To make life a little easier:
A mnemonic system for representing machine instructions
Mnemonic names for op-codes
Identifiers: Descriptive names for memory locations, chosen by the programmer

• Such a mnemonic system is called an assembly language


Programs called assemblers were developed to convert assembly language into machine
language

“mnemonic” ~ making something easier to remember


“2nd Generation”
Assembly language example

Machine language Assembly language

156C LD R5, Price


166D LD R6, ShippingCharge
5056 ADDI R0, R5 R6
30CE ST R0, TotalCost
C000 HLT

Assembly language is still used today whenever


precise and fast control of hardware is needed.
Historical Perspective (3)
• Assembly Languages were a big step forward,
but they have their limitations/problems:
– Primitives differ only in syntax
• One-to-one correspondence between machine instructions and assembly instructions
– Entirely machine dependent
• Programs developed on one machine cannot be easily transported to another computer design because
they must be rewritten to conform to the new computer’s register configuration and instruction set
– Programmer’s focus still on instructions - not the problem itself.
• No ‘high-level primitives’, larger units that better model the problem
Historical Perspective (4)
“3rd Generation”
• To make life much, much easier:
– Introduction of high-level primitives
• Similar to pseudocode
– Examples: Fortran, COBOL, Algol, BASIC, Pascal, C, Java, …
• Each primitive corresponds to a short sequence of machine language instructions
• Converted to machine language by a program called a compiler
High level language
For high-level languages we need a compiler,
a program that translates high-level language
programs into machine language.
• Machine-independent – high-level languages are not
designed with a particular type of computer in mind
• A program written in C can be executed on many
different types of computers (e.g. PC, Apple, Sun)
once we have a C compiler for the brand of machine.

Source code: a program written in a high-level language (e.g. Java,


C, Pascal)
Executable code: a program that has been translated (usually by an
assembler or compiler) into machine language code
Programming languages

High Level Language


temp = v[k];
Program (e.g., C) v[k] = v[k+1];
v[k+1] = temp;
Compiler
lw $15, 0($2)
Assembly Language
Program lw $16, 4($2)
sw $16, 0($2)
Assembler sw $15, 4($2)

Machine Language 0000 1001 1100 0110 1010 1111


Program 1010 1111 0101 1000 0000 1001
1100 0110 1010 1111 0101 1000
0101 1000 0000 1001 1100 0110
Hardware

°
°
Evolution of Programming Paradigms

• Paradigm:
– informally: ‘method of expression’ / ‘philosophy’
Programming Paradigms

• These represent different approaches to


building solutions to problems
• Software development paradigms
– Imperative / procedural
– Declarative
• Logic programming
– Functional
– Object-oriented
Imperative programming

An imperative program has:


• A set of data items (variables)
• A sequence of statements that evaluate expressions,
• Assignments that replace old values with new ones.

During programming, programmer must keep track of:


• The correct sequence of operations,
• The variables whose values are being used,
• The variables whose values are being replaced.

Which is difficult, especially for larger programs.


Declarative programming
• The programmer describes the problem to be solved,
rather than an algorithm to be followed
• More precisely, a declarative programming system
applies a pre-established problem-solving algorithm to
solve problems presented to it
– Programmer’s task is to develop a precise statement of the
problem
• Logic programming provided a general-purpose
problem-solving model for declarative programming
Functional programming
• The program is viewed as a function
– An entity that accepts inputs and produces outputs
• A program is constructed by connecting smaller pre-
defined program units (pre-defined functions) so that
one’s output becomes another’s input
– Building nested complexes of simpler functions
i.e. Functions of functions
– Examples: LISP, Scheme, ML, Haskell
– Example - the factorial function in Haskell:
let { fac 0 = 1; fac n | n > 0 = n * fac (n-1) }
Object-oriented programming
- Example: Smalltalk, Java, C#
- Data and methods are grouped into classes which are
used as templates to create objects
- Distinguish between public and private data and
procedures
private: available only within the object
public: available to other parts of the software
- Chief advantage is that it simplifies code reuse
- Can have multiple instances of an object because each
has its own data and procedures
- Inheritance: classes of objects are derived from other
classes (can share common procedures and data
structures)
6.2 Traditional Programming Concepts

• Language-statements fall into 3 categories:


– (1) declarative statements
• variables and data types
• data structure definitions
• constants
– (2) imperative statements
• assignment statements
• control statements
– (3) comments
Figure 6.4 The composition of a typical
imperative program or program unit
Figure 6.5 Variable declarations in C, C+
+, C#, and Java
Example of a Typical Imperative Program
/* program to manipulate a list */

functional unit #include <stdio.h>


declarative statements
#include <string.h>

int main()
{
char names[10][9], pivot[9];
int i, j;

/* get the names */


for (i=0; i<10; ++i) {
scanf(“%s”, names[i]);
} comments
imperative statements
/* sort the list */
for (i=0; i<10; ++i) {
strcpy(pivot, names[I]);
j = i - 1;
while ((j >=0) && (strcmp(pivot, names[j]) < 0)) {
(strcpy(names[j+1], names[j];
--j;
}
strcpy(names[j+1], pivot);

/* print the list */


for (i=0; i<10; ++i) {
printf(“%s\n”, names[i]);
}
}
Declarative statements: variables & data types

• Variables:
– descriptive name for location(s) in main memory
– declared in combination with data type
Declarative statements: data structures (1)
• Data Structures:
– arrangement of multiple data units (possibly of
different types)
– e.g.: homogeneous array, such as one-dimensional lists,
and two-dimensional tables (all elements of same type)

– declaration example in C: int Scores[2][9];


Declarative statements: data structures (2)

• Data Structures:
• e.g.: heterogeneous array, a block of data in which
different elements can have different types

(total: 14 bytes)
Declarative statements: constants and literals

• Constants:
– descriptive names for non-changeable values
– for better readability / understanding of code
• Example:
const WaterDensity20C = 998.2071
….
wMass = waterVol * WaterDensity
Q. A company’s number of employees rises from 5 to 6. Two
programs now must be altered to reflect this.
- Indicate what changes must be made.
- What problems arise in Program 1 that are avoided in Program 2?

Program 1: Program 2:

: :
DailySalary := TotalSal/5; NumEmpl constant Integer := 5;
AvgSalary := TotalSal/5; DaysWk constant Integer := 5;
DailySales := TotalSales/5; :
AvgSales := TotalSales/5; DailySalary := TotalSal/NumEmpl;
: AvgSalary := TotalSal/DaysWk;
DailySales := TotalSales/NumEmpl;
AvgSales := TotalSales/DaysWk;
:
Imperative statements: assignment
• Assignment:
– pseudo-code example: TotalCost  100
– requests that a value be stored in the memory area
identified by a variable
• General form:
– name  expression
– where ‘expression’ can be complex, and needs
evaluation before the assignment takes place:
• Z = X + Y;
• searchSuccessful = doSearch(namesList, ‘David’);
• result = 2 * 4 + 6 / 2; (operator precedence must be defined!!!)
Operator precedence

The expression 1 + 2 * 3 is ambiguous


Does this give result 9 = (1+2)*3
or 7 = 1 + (2*3) ?
In order to eliminate ambiguity, and reduce the need for
brackets, operator precedences are set:
Multiplication and division have precedence over addition
and subtraction (so above expression has value 7)
Check the rules for your programming language, and if in
doubt add brackets to force an order of execution
Overloading of operators

Many programming languages allow the use of one


symbol to represent more than one operation.
the meaning of the operator is determined by the
data type of the operands
e.g the symbol + can be used for addition of
numbers, and sometimes (e.g. in Java) for
concatenation of strings: “a” + “bc” = “abc”
Multiple use of an operator in this way is called
overloading
Q. What is the difference between the "equals" symbol in
if (X = 5) then ( . . . )
as opposed to the statement
X=2+Y

• The first '=' is a comparison function which


returns 'true' or 'false'.

• The second '=' is an assignment operation.


Imperative statements: control structures

• Control statements:
– change the
execution sequence
of a program
Imperative statements: control structures (2)
• Possible, but bad programming practice:
GOTO statement
goto 40
20 Apply procedure StayIndoors
Goto 70
40 If (PollutionLevel < Hazardous) then goto 60
Goto 20
60 Apply procedure GoOutdoors
70 . . .

c.f. If (PollutionLevel < Hazardous)


then (Apply procedure GoOutdoors)
else (Apply procedure StayIndoors)
Procedural / Functional Units
• Procedure:
– encapsulated set of instructions for performing a task that can
be used (called or invoked) by other program units
• Control:
– transferred to the procedure when called, and returned back
to original program when finished
The procedure ProjectPopulation written in C
Parameters
• Procedures usually written using generic terms
– write once - use many times for manipulation of
different blocks of data
– example: procedure Sort(List)
• Generic terms:
– parameters
• used in writing procedure: formal parameters
e.g.: void ProjectPopulation( float GrowthRate, int BaseValue )
• used in applying procedure: actual parameters
e.g.: rate = 17.3;
ProjectPopulation( rate, 100 );
Figure 6.12
Executing the
procedure Demo and
passing parameters
by value
Figure 6.13
Executing the
procedure Demo and
passing parameters by
reference
Parameters - pass by value / pass by reference

• Parameter Passing:
– (1) pass by value
calling environment procedure’s environment
actual formal
5 does not change! 16
5

– (2) pass by reference (the address of actual parameter)


calling environment procedure’s environment
actual formal
16
5 does change!
Q. Suppose a procedure 'Modify' is defined by
procedure Modify(Y)
Y := 7;
print the value of Y;

If parameters are passed by value, what is printed when the


following program is executed? And what if passed by reference?
X := 5;
apply the procedure Modify to X;
print the value of X;

• By value: 75 is printed
– value of ‘X’ is given to Modify, but ‘X’ cannot be changed

• By reference: 77 is printed
– address of ‘X’ is given to Modify, so ‘X’ can be changed
Functions
• Function:
– procedure that produces a value (rather than
performing an action only)
– produced value is returned back to the calling
program unit

• Example: float CylinderVolume( float Radius, float Height )


{
floatVolume;

Volume = 3.14 * Radius * Radius * Height;


return Volume;
}

• Usage: Cost = CostPerVolUnit * CylinderVolume( 3.45, 12.7 );


Imperative vs. Object-Oriented (1)

• Imperative example: #define MAX-SIZE 8

typedef enum { OK, FULL, EMPTY } stack_state;

typedef struct {
int table[ MAX_SIZE ];
13 int top;
stack_state state;
32 } Stack;

65 void push( Stack *s, int element )


{
97 ( s->state != FULL ) ? (s->table[(s->top)++]==element) :
printf( “*** Stack full ***\n” );
48 s->state = (s->top >= MAX_SIZE) ? FULL : OK;
}
17
int pop( Stack *s )
33 {
int element = 0;

Stack (state=OK, top=5


top=4)
top=7
top=6 ( s->state != EMPTY ) ? (element = s->table[--(s->top)) :
printf( “*** Stack empty ***\n” );
s->state = (s->top <= 0) ? EMPTY : OK;

return element;
}
Imperative vs. Object-Oriented (2)

• Disadvantages of imperative Stack-code:


– no relation enforced between ‘Stack’-definition &
‘Stack’-operations ‘push()’ and ‘pop()’
• potential difficulties in understanding large programs,
as each program unit could directly relate to any other
– worse even: other program units can freely change
‘Stack’-data without using ’Stack’-operations
• all program units need to be checked when ‘Stack’-
definition is changed
• difficult to maintain consistent & bug-free code
Imperative vs. Object-Oriented (3)

• OO-paradigm bypasses these problems by:


– definition of objects: combined specification of
data structure & operations on that data
– encapsulation: restricting (or even: denying)
access to objects internal properties
• by definition of ‘public’ & ‘private’ data + operations
– public: accessible by other program units
– private: hidden from other program units
• in other words: separation of object implementation
Imperative vs. Object-Oriented (4)
#define MAX-SIZE 8

typedef enum { OK, FULL, EMPTY } stack_state;

• OO stack-example: class Stack {


public: void push ( int );
int pop();
put together what private: int table[ MAX_SIZE ];
belongs together... int top;
stack_state state;
...show only what };
needs to be shown
void Stack::push( int element )
{
(state != FULL) ? (table[top++]==element) :
cout << *** Stack full *** << endl;
97 state = (top >= MAX_SIZE) ? FULL : OK;
}
48
int Stack::pop()
17 {
int element = 0;
33
(state != EMPTY ) ? (element = table[--top]) :
cout << *** Stack empty *** << endl;
Stack (state=OK, top=4) state = (top <= 0) ? EMPTY : OK;
return element;
}
6.4 Language Implementation

• Translation / Compilation:
– converting high-level language code into machine language

3 stages of activities:
lexical analysis
parsing
code generation
– Lexical analyser:
• recognizes / classifies strings of symbols into single entities
(tokens)
• token packages each unit and its classification
• all program comments are ignored
Lexeme Token
int maximum(int x, int y) { int Keyword
if (x > y) return x;
maximum Identifier
else
return y; ( Operator
} int Keyword
x Identifier
– Parser (syntax analysis):
• groups lexical units(tokens) into statements (i.e. finds the
grammatical structure)
• based on ‘syntax diagrams’

A syntax diagram of an if-then-else statement


In order to simplify parsing many early programming
languages were fixed-format languages - each program
statement had to be positioned in a particular manner on the
printed page
Now most languages are free-format languages, and program
code can be laid out in a way that improves readability from
a human’s point of view
Free-format languages use punctuation marks and keywords
(e.g. if, else, while) to mark beginnings and ends of phrases
The keywords are usually reserved words – meaning that the
programmer cannot use them for other purposes in the
program
– Code Generator:
• constructs sequences of machine instructions from the
statements recognized by the parser
• producing efficient machine-language versions of
programs requires code optimisation
e.g. in translating
x = y + z;
w = x + z;
transfers of data between main memory and CPU can be
avoided by recognising that at the end of the first
statement the values of x and z are already in the CPUs
registers
Syntax diagrams and parse trees
• A grammar is a set of rules defining the syntax of a
language
• The grammar rules may be expressed as syntax
diagrams
e.g. a syntax diagram of an if-then-else statement:

Terms in rectangles are nonterminals and require further


description.
Terms in ovals are terminals.
Figure 6.19 An object-oriented approach
to the translation process
Complete Program Preparation Process

• Object program usually not executable


• Often needs to work together with other modules
• Modules must be connected to create executable code

– Linker:
• connects several object programs to produce executable program
(usually in form of: program.exe)
– Loader:
• places program code in main memory
• notifies OS scheduler
Chapter 6 - Programming Languages:
Conclusions
• High-level languages
– allow concentration on problem to be solved
– important property: machine independence
• Multiple programming paradigms
– most popular: imperative & object-oriented
• General program statements:
– declarative, imperative, comments
• Procedure calls:
– generic due to parameter passing (by value or reference)
• Imperative vs. Object-Oriented
– OO encourages putting together what belongs together
Software - Programming Languages

General purpose programming languages


FORTRAN Physics, Math, Engineering
COBOL Business oriented
APL Math, scientific
GPSS Simulation
Lisp Artificial intelligence - Functional programming
PL/1 Application oriented
C Systems and applications programming
C++ Object oriented
Java Platform (OS) independent object oriented
Terminology

Machine language Makine dili


Assembly language Çeviri dili
High-level language Yüksek düzey dil
Language processor Dil işleyici
Assembler Çevirici
Compiler Derleyici
Interpreter Yorumlayıcı
Structured programming Yapısal programlama
Object-oriented programming Nesneye-yönelik programlama
Functional programming İşlevsel programlama
Terminology

Medium (Plural: media) Ortam


Communications medium İletişim ortamı
Block structured (language) Blok yapılı (dil)
Record Kayıt
Activation Record Etkinleştirme kaydı
Scope Kapsam
Nesting (içerde) yuvalanma
Stack Yığın
Procedure Prosedür/Yöntem
Routine Yöntem/Usül
Subroutine Alt-prosedür

You might also like