Programming Languages
Programming Languages
- A programming language is a set of symbols in computer language that are used in coding
computer programs.
- A programming language is a specially written code used for writing application programs e.g.
C, Pascal, COBOL, BASIC, Visual Basic, C++ and Java (Originally for intelligent consumer-
electronic devices (cell phones), then used for creating Web pages with dynamic content, now also
used for developing large-scale enterprise applications)
- Program: a set of detailed and unambiguous instructions that instructs a computer to perform a
specific task, for example, to add a set of numbers.
- Programming: A process of designing, coding and testing computer programs
- Programmer: A person who specialises in designing, coding and testing computer programs
- Problem: any question or matter involving difficulty or uncertainty and is proposed for a computer
solution.
b. Assembly Language:
- These are programming languages that use mnemonic codes in coding programs.
- Mnemonic codes are abbreviations used to represent instructions when coding assembly language
programs, for example, LDA for Load, ADD for Addition, etc.
- One assembly language statement is equivalent to one machine code instruction and therefore
programming lengthy and time consuming.
- However, assembly language programs are efficient.
- Programs also run faster as they are closer to machine language and therefore are used in
designing programs that needs efficient timing, e.g. games like chess, operating systems, etc.
- Assembly language is used when there is need to access registers and memory addresses directly.
- Assembly language instructions also occupy very little disc storage space.
- Programs written in High Level Language are first converted to machine code before running.
High level languages have the following features:
- Problem oriented (Machine independent): they are designed to solve an application problem and
therefore runs on any machine
- They are portable: they can be transferred from one machine to another and run without problem.
- Instructions are written in English statements which are easier to understand.
Disadvantages of HLL
- Takes long to run since they need to be first converted to machine code.
- They occupy a lot of disk storage space as compared to low level languages.
What Is an Object?
Objects
- are real world items that have state (attributes) and behaviour (operations) and belong to certain
class, e.g. desk, car, television set, bicycle, etc.
- In general, an object is an instance of a class and is an actual real-world entity.
State:
Behaviour (operations):
- Refers to methods that can be used on each object state, e.g. changing gear of a car, applying
brakes, etc.
- Each class has its source code that is associated with it and defines the fields and methods.
- Dogs have behaviour (barking, fetching, wagging tail).
Class:
- A set of objects which share a common data structure and a common behaviour.
- In coding a program, a class is taken as an abstract data type that describes the fields and methods
of the class.
- Each class has different access levels, which can be private, protected or public.
- Example of class declarations in Java are as follows:
class Bicycle {
int speed = 0;
int gear = 1;
void changeGear(int newValue) { gear = newValue; }
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) { speed = speed - decrement; }
void printStates() {System.out.println(speed:"+speed+" gear:"+gear); }
}
Encapsulation
- This is a technique of combining operations (methods) and data (fields) into one unit as in classes.
- Encapsulation can be in two forms:
(a) Data encapsulation: Hiding states internally and requiring all interaction to be performed
through an object's methods. It involves restricting access to the states (fields).
(b) Procedural encapsulation: users do not need to know how the behaviour happens, that is
hiding operations from the user.
Inheritance
- In Object-oriented programming, inheritance is whereby classes can re-use (assume) commonly
used state and behaviour from their parent (base) class.
- Inheritance is the ability of a class to use the variables and methods of a class from which the new
class is derived (parent class)
- Inheritance allows a new class to be derived from an existing class.
- Inheritance therefore is a relationship among classes, where a sub-class (derived class) shares all
the fields and methods of the base (parent) class, plus its own methods and states.
- Consider the inheritance diagram below:
- Base Class: This is the parent class or the first class to be created from which other class can
inherit states and methods.
- Derived class: These are new classes that are created from the base class, and therefore have
methods and states of the base class plus their own methods and states.
- The syntax for creating a subclass is use the extends keyword, followed by the name of the class to
inherit from:
class MountainBike extends Bicycle
{
// new fields and methods defining a mountain bike
// would go here
}
Polymorphism
Containment/aggregation/composition
- These are links/associations between objects that allow them to communicate.
- For instance: a form on a screen is an object. On the object form, there are other objects, e.g. delete
button, display button, exit button, etc.
- These buttons (which are objects) communicate with the form (another object).
- Thus the linkage between the form and the buttons is called the containment.
Event handlers: small program codes which are invoked (called) in response to external events.
Dispatcher: small program codes that call event handlers so that events can be processed.
Advantages of OOP
Grouping code into individual software objects provides a number of benefits, including:
- Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Once created, an object can be easily passed around inside the
system.
- Information-hiding: By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
- Code re-use: If an object already exists, you can use that object in your program.
- Easy debugging: If a particular object turns out to be problematic, you can simply remove it from
your application.
- Reliability: if codes are designed by specialists, they are more likely to free from errors due to
intensive testing.
- Time saving: re-use of existing methods and states means less time needed to code programs.
- Smaller program codes: since the states and methods of classes are re-used, the code of the
program is smaller, taking less disk storage space.
- Storage structures of an object may be altered without affecting the programs that make use of it.
Object Code
- Refers to a machine code version of a source code.
- All programs written in source code must be converted to object code for the computer to
understand them.
TRANSLATORS
- These are programs used to convert High level Language programs as written by the programmer
(source code) into machine code that the computer can execute.
- Translators are in three types, which are assemblers, interpreters and compilers, which are
further explained below:
1. Assemblers:
- These are programs used to translate assembly language instructions (program) into machine
language instructions before execution.
- Since each computer has its own assembly language, it also has its own assembler.
- Assembler programs are written either using assembly language, or using high level languages like
C.
- Assemblers are simpler to program as compared to compilers.
- Assemblers are in two types: One-Pass Assemblers and Two-Pass Assemblers
One-Pass Assemblers
- These go through the source code once and assume that all the symbols will be defined before
any instruction that reference them. This is equivalent to declaring variables at the top of the
source code regardless of where they are used in a high level language program.
- It has an advantage of speed since only one phase in gone through
Two-Pass Assemblers.
- Creates a table with all the symbols and their values in the first pass and then use the table in
the second pass to generate code.
- Has an advantage that symbols can be defined at any stage in the source code.
- Two-pass assemblers make programs easier to read and to maintain.
Uses of Assemblers
- The uses of assemblers include:
They generate machine code that is equivalent to assembly language.
They are used to check the validity of instructions, that is, checking for syntax errors in an
instruction.
They also assign memory locations to variables.
2. Interpreters
- These are programs that translate and run one (command) instruction of a program at a time
before going to the next instruction until the end of the program, e.g. the BASIC interpreter.
- Interpreter must be present to run the program. It is used during program writing (coding) because
it easily aids in debugging.
- An interpreter translates one instruction at a time and then executes it.
- They do not produce the machine code version (object code) of a program; hence translation is
repeated every time the program is executed.
Compiled by Kapondeni T. Page 8 of 27
- If the program is run 100 times, translation for each instruction is also carried out 100 times.
Functions of Interpreters
- They translate each instruction in turn into machine language and run it.
- Allocates storage space to variables.
- They check syntax error in a program statement.
- Gives error messages to the user
- Finds wrong and reserved words of the program
- Determines wrong use of variables
Advantages of interpreters
- It is easy to find and correct syntax errors in interpreted programs.
- There is no need for lengthy recompilation each time an error is discovered.
- It is very fast to run programs for the first time.
- Allows development of small program segments that can be tested on their own without
writing the whole program.
- It is easier to partially test and debug programs, especially during the programming stage.
- It is very fast to run small programs.
- individual segments can be run, allowing errors to be isolated
- running will be necessary after very minor changes
- continual compilation of whole code is wasteful/time consuming
Disadvantages of interpreters
- They are very slow in running very large programs.
- They do not produce an object code of a source code and hence difficult to use since
conversion takes place every time the program is run.
3. Compilers
- These are programs that convert a high level language program into its machine code equivalent at
one go (at once) and then run it, e.g. the COBOL compiler.
- Compiler must be present for compiling the program.
- Once compiled, the program no longer needs conversion since the machine code version is the one
that will be run, until some changes are made to the program code.
- Compilers run faster when called and therefore may be held as library routines.
- Once compiled, the program can then be run even on a computer without the compiler since the
program will already be in machine code.
- The compilation processes involves many complex stages which will be looked later in this course.
Functions of Compilers
- They check syntax errors in program statements.
- They allocate storage space to variables.
- Translate the whole program into machine code at one go.
- Run object code of the program.
- Produces a program listing which indicates position of errors in a program.
- Gives error messages to the user
- Finds wrong and reserved words of the program
- Determines wrong use of variables
Advantages of Compilers
- The object code can be saved on the disc and run when needed without the need for
compilation.
- Compiled programs run faster since only the object code is run.
Disadvantages of Compilers
- Slower than interpreters for running programs for the first time.
- They can cause the computer to crash.
- Difficult to find errors in compiled program.
- There is need for lengthy recompilation each time an error is discovered.
5. Variables
- A variable is a name given to a memory location that stores a certain value, which may change
(the value) during program execution.
- Variables can be field identifiers, e.g. surname is a valid variable name.
- Variables must not be reserved words.
- Variables must be unique in the procedure or program (if all are global).
a. Global variables
- These are variables that are accessed and can be used by any procedure or function within the
same program.
- They are public variables
- The value of the variable exists throughout the program.
- Global variables are declared outside the procedure.
- In VB 6.0, global variables are declared as follows:
Public Sname As String
The word Public implies that it is a global variable.
b. Local variables
- These are variables that are defined within a procedure and that are accessible just within the
procedure they are declared.
- They are defined within the procedure.
- They are private variables
- The value of the variable only exists within the procedure it is defined.
- They are therefore local to that procedure in which they are declared and therefore cannot be
used (not accessible) by other procedures.
- Local variables are declared as follows:
Private Sname As String
6. Reserved words
- Reserved (key) words are identifiers with a pre-defined meaning in a specific programming
language, for example Dim, if, End, integer, As, etc. in Visual basic.
- Reserved words must not be used as variables.
- Each programming language has its own reserved words, which may differ from other
languages.
- translator program maintains a dictionary of reserved words
- if the reserved word used is not in this dictionary then an error has been made and message
may be given which suggests one close to spelling provided
7.
Expressions
- An expression is a construct made up of variables and operators that makes up a complete unit
of execution.
Example:
NumberA = a+b-c*d
- The above is a statement. However, a+b-c*d is an expression found in a statement.
- Expressions can be arithmetic (as given above), Boolean or string expressions. For example,
(a>b) and (a>=c)
- Operator precedence is very important in evaluating expressions and therefore it is important to
enclose expressions is brackets where possible. Operator precedence is as follows, starting from
the highest to the lowest:
( ), Not, ^, {*,/,}\,Mod, {+, -,}{=,<,>,<=, >= },…
NB: Operators is set braces indicates that they are in the same level.
- Arithmetic expressions are evaluated first, followed by comparisons and lastly logical
expressions.
8. Statements
- A statement is a single instruction in a program which can be converted into machine code and
executed.
- A statement can just be one line of program code but in some cases a statement may have more
than one line.
- For example: Name = “Marian” is a statement.
Example 1
NumberA = a + b
- this is an assignment statement, that is, variable NumberA is assigned the sum of the values of
variables a and b. thus if a=2 and b = 3, NumberA is assigned the value 5.
- An assignment is an instruction in a program that places a value into a variable, e.g total = a + b
Compiled by Kapondeni T. Page 13 of 27
- The above is just one line statement.
Example 2
If a>b Then MsgBox "a is bigger than b.", vbExclamation
- The above is a one line statement composed of if statement.
Example 3
If b < 0 Then
MsgBox "b is less than zero. Command cannot be executed", vbExclamation
Exit Sub
End If
- This is a statement (starting at the first if and ending at End If.
- This state comprises of other statements between it.
9. Block structure
- A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed. For instance
if (condition) Then ( begin block 1)
………………. (end block 1)
else (begin block 2)
……………….
End If (end block 2)
10. Functions
- A function is a self-contained module that returns a value to the part of the program which
calls it every time it is called/executed.
- A function can be just an expression that returns a value when it is called.
- A function performs a single and special task, e.g. generate a student number.
- Because they return a value, functions are data types, e.g. integer, real, etc.
- Functions can be in-built functions or user-defined functions.
- In-built functions are pre-defined procedures of a programming language that returns a value,
e.g. Val (returns a numeric value of a string), MsgBox (creates a textbox on the screen), Abs
(returns an absolute value of a number), etc.
- Visual Basic has in-built date functions, string functions, conversion functions, etc.
- A user-defined function is a procedure (module) that returns a value whenever it is called. The
structure of a user defined function is as follows:
Public Function count_rec(ByVal rs As Recordset) As Boolean
If rs.RecordCount <= 0 Then
MsgBox "There is no record in the table.", vbExclamation
count_rec = True
Else
count_rec = False
End If
End Function
- Note that a Function starts with the word Function and ends with the statement End Function.
This function returns a Boolean value(either true or false). The function name as just after the
word Function, i.e count-rec in the case above.
11. Procedures
- A self-contained module that does not return a value.
- Procedures usually starts with the key word Procedure and then procedure name, e.g
Procedure FindTotal. Procedures are user defined.
- The name of the procedure should be related to its task
- Each procedure name must be unique within the same program.
- A procedure can be called from the main program or by other modules.
Compiled by Kapondeni T. Page 14 of 27
- A procedure is called by stating it name
- Parameters are usually passed when calling procedures.
- Parameters/arguments are values that are passed from one procedure to another and can be
the actual values or variable names. They are therefore values given to a function by
statements from other modules.
- Parameters can be formal or actual parameters
Actual parameters: these are arguments found in the calling module/statement, could be
variables or actual data like 30, 40.
Formal parameters are those variables that receive data from calling module or statement.
- When processing of the called procedure is finished, processing goes to the next stated after
the calling statement.
- Parameters can be passed by value or by reference
- If the programmers does not specify ByVal or ByRef function, Visual Basic assumes that it if
ByRef by default.
12. Semantics
The meaning attached to statements and the way they are used in a certain language.
13. Syntax
- These are grammatical rules and regulations governing sentence construction and layout of
different programming languages.
- For example, Pascal uses a semi-colon(;) at the end of each instruction, it also uses the reserved
(key) word writeln to display items on the screen, etc.
- Each programming language has its own syntax.
- A program with syntax errors does not run.
14. Literals
- A literal is a variable which is given a fixed value within the code of the program.
- A literal is the source code representation of a fixed value.
- Literals are represented directly in your code without requiring computation, as shown:
DATA TYPES
- Data types describe the nature of data handled by programs.
- These are important as they enhance program readability and maintenance.
- Data types can be simple (integers, string, etc.) or complex (arrays, lists, records, etc.).
- Data types are declared at the beginning or at some point inside the program code.
- Data types for variables must be properly declared.
Variable length:
Does not specify the number of characters, each data items occupies the number of spaces it
requires.
This is declared as follows
Dim Sname as string
2. Boolean
- Represents instructions that evaluate to either True or False only. The default value is
False and occupy 2 bytes of storage.
- Mostly used together with If….. Then……. Else Construct.
3. Character
- A data type that holds just one alphabetic or special character like %, $, a, etc.
- can be written as char in most programming languages.
User-defined data.
These are defined by the user depending on the method of solution, e.g classes when the used define
own classes.
Enumerated data:
These are data types with a list of items that are pre-defined, e.g days of the week, months of the year,
etc.
Word: a computer word is group of bits that can be handled or transferred by the processor as a
single unit (word length).
Disadvantages of Modularisation
- Documentation will be long and thorough, therefore may take time to produce
- Can lead to problems of variable names as the modules are developed separately.
- However, it may be difficult to link the modules together.
*NB: Library programs: this refers to a collection of standard pre-written programs and subroutines
that are stored and available for immediate use by other modules in the system.
Library programs are programs that are required by other modules during execution, e.g. the Dynamic
Link Libraries (DLL) in the Windows environment.
Libraries contain common tasks like saving, deleting, etc.
Library programs are referenced by most modules in the systems and they provide data to other
modules.
*NB: Stepwise refinement: a technique used in developing the internal working of a module.
To stop this we use the fact that, eventually, <integer> is a single digit and write
<integer> ::= <digit>|<digit><integer>
We now have the full definition of an unsigned integer which, in BNF, is
<unsigned integer> ::= <digit>|<digit><unsigned integer>
<digit> ::= 0|1|2|3|4|5|6|7|8|9
Variables in BNF
Valid variables start with a letter (Upper or lowercase) and followed by any character (which must be
a letter, digit or underscore) upt to any length. This can be defined in BNF as:
<variable> ::= <letter>|<variable><character>
<character> ::= <letter>|<digit>|<under-score>
<letter> ::= <uppercase>|<lowercase>
<uppercase> ::= A|B|C|D|E|F|G|H|I|J|K|ZL|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z
<lowercase> ::= a|b|c|d|e|f|g|h|i|j|k|zl|m|n|o|p|q|r|s|t|u|v|w|x|y|z
<digit> ::= 0|1|2|3|4|5|6|7|8|9
<under-score> ::= _
The above can be illustrated in a syntax diagram as:
Lexical Analyser
Syntax Analyser
Semantic Analyser
Code Generator
Code Optimiser
Object Code
Analysis Phases
Consists of the lexical analyzer, syntax analyzer and the intermediate code generator.
Lexical Analysis
This is where scanning of the source program is done. Each sequence of characters that have
an atomic meaning are recognized and represented by a token.
A token represents a class of valid letters, for example a program is going to analyse numbers,
variables and functions.
Syntax Analysis
This is the stage where tokens are grouped into large structures, for example, assignment
statements.
Semantic Analysis
This is where there is transition of tokens into code generation and complex errors are
detected.
Synthesis Phase
This phase consists of the Code Optimiser and Code Generator.
Code Generation
Code Optimiser
There is reduction of the number of instructions in order to allow the program to run faster.
Linkers
REVIEW QUESTIONS
1. Explain the terms
(i) data encapsulation
(ii) inheritance
(iii) Polymorphism
when applied to programming in an object oriented programming language. (4)
2. Distinguish between procedural languages and declarative languages. (4)
3. Explain the passing of parameters by reference and by value. (4)
4. (a) Explain the difference between the translation techniques of interpretation and compilation [2]
(b) Give two advantages of each of the two translation techniques. [4]
5. An amount of money can be defined as
• A $ sign followed by either
• A positive integer or
• A positive integer, a point, and a two digit number or
• A point and a two digit number
A positive integer has been defined as <INTEGER>
A digit is defined as <DIGIT>::= 0/1/2/3/4/5/6/7/8/9.
a) Define, using Backus Naur form, the variable <AMOUNT OF MONEY>
b) Using the previously defined values of INTEGER and DIGIT, draw a syntax diagram to define
AMOUNT OF MONEY.
6. State the three stages of compilation and briefly describe the purpose of each. [6]
7. Explain in detail, the stage of lexical analysis. [6]
8. Explain the role of
(i) linkers,
(ii) loaders
in the running of programs [4]
9. Two of the stages which a high level language program undergoes during compilation are lexical
analysis and syntax analysis.
Discuss how errors are discovered during each of these two stages. [5]
10. (a) (i) Describe what is meant by source code. [2]
(ii) Explain why source code needs to be translated into object code. [2]
(b) State what is meant by the following types of programming error:
(i) syntax error [1]
(ii) arithmetic error [1]
11. (a) Explain how the translator program prepares the programmer’s code into a program that the
machine can run. [2]
(b) (i) Explain what is meant by a procedure. [2]
(ii) Describe how procedures and the programming construct “selection” can be used to code a
simple menu system for a user. [3]
12. (a) Explain the difference between interpretation and compilation of a program written in a high
level language. [2]
Compiled by Kapondeni T. Page 25 of 27
(b) Explain what happens during the lexical analysis stage of compilation. [5]
(c) Describe two things that happen during code generation. [4]
19. In a particular object oriented programming language, the following classes are defined