0% found this document useful (0 votes)
16 views41 pages

CSC Survey Programming Language

The document outlines the course content for CSC321: Survey of Programming Languages at Sule Lamido University, covering the history, paradigms, and semantics of programming languages, as well as their evolution and roles in computing. It emphasizes the importance of understanding programming languages for algorithm development, effective programming, and the design of new languages. The document also categorizes programming languages into generations and discusses various high-level languages, their features, and the translators used for converting them into machine-readable forms.

Uploaded by

abbagamji1256
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views41 pages

CSC Survey Programming Language

The document outlines the course content for CSC321: Survey of Programming Languages at Sule Lamido University, covering the history, paradigms, and semantics of programming languages, as well as their evolution and roles in computing. It emphasizes the importance of understanding programming languages for algorithm development, effective programming, and the design of new languages. The document also categorizes programming languages into generations and discusses various high-level languages, their features, and the translators used for converting them into machine-readable forms.

Uploaded by

abbagamji1256
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF COMPUTER SCIENCE

FACULTY OF COMPUTING
SULE LAMIDO UNIVERSITY, KAFIN HAUSA
CSC321: SURVEY OF PROGRAMMING LANGUAGES

Course Content
Overview of programming languages: History of programming languages, Brief survey of
programming paradigms (procedural languages, Object-oriented languages, Functional
languages, Declarative-non-algorithmic languages, scripting languages). The effects of scale on
programming methodology; Languages Description: Syntactic structure (Expression notations,
abstract Syntax Tree, Lexical Syntax, Grammars for Expression, variants of Grammars),
Language semantics (Informal semantics, Overview of formal semantics, Denotation semantics,
Axiomatic semantics, Operational semantics); Declarations and types: The concept of types,
Declaration models (binding, visibility, scope, and lifetime), Overview of type-checking,
Garbage collection; Abstraction mechanisms: procedures, function, and iteration as abstraction
mechanism, parameterization mechanisms

A. Learning Objectives
At the completion of this note, it‟s expected that learners will achieve the following:

1. Learn some basic concepts on the evolution of programming languages


2. Be familiar with language definition structure
3. Identify different data types supported by selected programming languages
4. Review of implementation approaches of the data types in some languages ( C, Java,
Python and VBscript)
5. Know the basic design issues in compiler construction for some selected languages
6. Understand program translation processes
7. Be able to write and differentiate the various ways of writing programs in C, Java,
Python and VBscript languages.

1
SECTION A: HISTORY AND BASIC CONCEPTS IN PROGRAMMING LANGUAGES

Computer Programming: A General Introduction


Computer programming is the craft of writing a set of instructions that can later be compiled
and/or interpreted and then inherently transformed to an executable that computer system or
other electronic machine can execute. A programmer is expected to master the syntax and
semantics of the programming language while at the same time understand the logic require for
each problem. Programming languages are artificial languages while human languages are
natural.

A programming language can be described by the combination of its semantics, syntax and
pragmatic. Syntax is concerned with how expressions, command declaration and other
constructs must be arranged to make a well-formed program. Semantics is concerned with the
meaning of programs and how a well-formed program is expected to behave when executed.
Pragmatics is concerned with the way in which the language is intended to be used in practice.

Programming is a very essential aspect of computing, because in it lies the power of innovative
thinking that can aid in developing rich software solutions. To be able to program well, one
needs to have passion for problem solving and continuous learning. A program is a set of
instructions that tell the computer to do various things; sometimes the instruction it has to
perform depends on what happened when it performed a previous instruction.
Reasons for Studying the Concepts of Programming Language
The reasons for studying the concepts of programming languages are as follows:

1. To improve your ability to develop effective algorithms


Having a basic knowledge of the principles and implementation techniques of programming
languages allows the programmer to understand the cost of techniques in one language compared
to another. For example to use concepts like OOP, logic programming, concurrent programming
requires an understanding of languages that implement the concepts.

2. To improve your use of existing programming languages


When the features of a programming language is well understood, the ability to write efficient
programs will increase.

3. To increase your vocabulary of useful programming constructs


By studying different programming language constructs, a programmer increases his
programming vocabulary. Therefore the understanding of implementation techniques is
important so that when one language does not provide a construct, the programmer can easily
think of other programming languages that can be used.
2
4. To allow better choice of programming languages

Programming languages are many and there is a need to identify the features of each language
while solving problem. A knowledge of different languages allows making just the right choice
for a project at hand. It would be easier to know language best suited for mathematical
application, AI application or business application as the case may be.

5. To make it easier to learn a new language


Having a sound knowledge of variety of programming language constructs and implementation
techniques makes it easier for programmer to learn a new programming language easily.

6. To make it easier to design a new language


It would be easier to device better approaches for designing new languages if the existing
languages are well studied to know its strengths and weaknesses.

7. Advancement in computing
Studying programming languages leads to an overall advancement in computing because state of
the art application can be easily designed to solve current and challenging problems.

Roles of Programming Languages


Programming languages evolve and eventually pass out of use. Algo from 1960 is no longer used
and was replaced by Pascal which in turn was replaced by C++ and Java. In addition, the older
languages still in use have undergone periodic revisions to reflect changing influence from other
areas of computing. As result, newer languages reflect a composite of experiences gain in the
design and use of older languages. An example of C++ evolution history over the years is
depicted in the figure below.

Having stated that, the roles of programming language are:-

1. To improve computer capability

3
Computer have evolve from the small, old and costly vacuum tubes machine of the 1950`s to the
super and microcomputers of today. At the same time layer of OS software have been inserted
between the programming language and the underlying computer hardware. This factors have
influence both the structure and cost of using the features of high-level language.

2. Improved application

Computer use has moved rapidly from the original concentration on military, scientific business
and industrial application where the cost could have been justified to computer games, artificial
intelligence, robotics, machine learning and application in learning of every human activity. The
requirements of these new application areas influence the designs of new language and the
revision and extension of older ones.

3. Improved programming method

Language designs have evolved to reflect our changing understanding of good method for
writing large and complex programs. It has also reflected the changing environment in which
programming is done.

4. Improved implementation method

The development of better implementation method has affected the change of features in the new
languages.

5. Standardization

The development of language that can be implemented easily on variety of computer system has
made it easy for programs to be transported from one computer to another. This has provided a
strong conservative influence on the evolution of language designs.
Attributes of a Good Program
Despite the importance of external influence, the programmer ultimately determines which
language stand the test of time or which language is in high demand. Many reasons explain why
programmer prefers one language to another some of the reasons are:

1. Clarity, simplicity and unity

4
2. Orthogonality (operations change just one thing without affecting others)
3. Naturalness is the anticipation
4. Support of abstraction
5. Ease of problem verification
6. Programming environment
7. Portability of program

1. Clarity, simplicity and unity


A good programming language should be an aid to the programmer by providing a clear, simple
and unified set of concepts that can be used as primitives in developing algorithms. As for
simplicity, a good programming language should have property in which constructs that mean
different things look different, that is semantic difference should be clear in the language syntax

2. Orthogonality

This refers to the attribute of being able to combine various features of a language in all possible
combinations, with every combination being meaningful. Orthogonality feature makes it easier
to learn a programming language it also makes it easier to write program because there are fewer
exceptions.

3. Naturalness for the application

A good programming language should provide appropriate data structures, operations, control
structures, and a natural syntax for the problem to be solved.

4. Support for abstraction

An ideal programming language should allow data structures, data types and operations to be
defined and maintained as self-contained abstractions.

5. Ease of program verification

The process of verifying that a program is correct should be easy because it is of great concern to
the reliability of the program. Ease of verification is made easier by the simplicity of semantic
and syntactic structure.

5
6. Programming environment

The availability of a reliable, efficient and well-documented implementation of a language is


important. This ensures that the speed of creation, testing, maintaining and modifying large
programs much simpler.

7. Portability of programs

Good programming language should have the attributes of transportability. That is, it should be
easy to move program projects from the computer on which they are developed to other
computer systems. In order words, the definitions of the program should be independent of the
features of a particular machine.
Taxonomy of Programming Languages
Programming languages are classified into five (5) generations based on the level of abstraction.

1. Low Level Language


2. High Level Language
3. Middle Level Language
4. Very High Level Language
5. Higher Level Language

1. Low Level Languages

Low-level languages are written in the language that the computer understands i.e Zeros (0‟s)
and ones (1‟s). Such languages have little or no abstraction between them and the machine
language. Hence, compilers and interpreters are not required. The use of low-level language
requires in-depth knowledge of computer architecture. The two types of languages in this
category are Machine and Assembly language. Machine language uses binary digits 0”s and 1‟s
while Assembly language uses alphanumeric symbols called Mnemonics (MOV, ADD, JMP.
Etc.). Machine language is the first generation computer languages while Assembly language is a
2nd generation language

Features of Low Level Languages

a. Fast processing: All the computer instructions are directly recognized. Hence, programs
run very quickly.
6
b. No need of Translator: The machine code is the natural language directly understood by
the computer. Therefore, translators are not required. Assembly language on the other
hand requires assemblers for conversion from mnemonics to equivalent machine code.
c. Error prone: The instructions are written using 0's and 1's. This makes it a herculean
task. Hence, there are more chances of error prone codes in these languages. Errors are
reduced in assembly language when compared to machine language.
d. Difficult to use: The binary digits (0 and 1) are used to represent the complete data or
instructions, so it is a tough task to memorize all the machine codes for human beings.
Assembly language is easier to use when compared to machine language.
e. Difficulty in debugging: When there is a mistake within the logic of the program then it
is difficult to find out the error (bug) and debug the machine language program.
f. Difficult to understand: It is very difficult to understand because it requires a
substantial knowledge of machine code for different system architectures.
g. Lack of portability: They are computer dependent such that a program which is written
for one computer cannot be run on different computer because every computer has
unique architecture.
h. In-depth Knowledge of Computer Architecture: To program in the Assembly
languages, the programmer need to understand the computer architecture as well as the
machine languages.

2. Middle-Level Languages
Middle-level languages bridge the gap between high-level and low-level languages. Examples of
these languages include C#, C++, and Java. They are used for designing graphical user interfaces
(GUIs) on personal computers. Middle-level languages are closer to human language when
compared to low-level languages.

Features of Middle-Level Languages

a. They have the feature of accessing memory directly using pointers.


b. They use system registers for fast processing
c. They support high-level language features such as user friendly nature;

3. High-level Languages
7
High-level languages allow complex sequences of processor instructions. They are mainly
written in format close to English language that can be easily understood by the human being.
Being written in human language however, leads to the use of compilers and interpreter that can

convert into the machine language equivalent. This category of languages are used for writing
large pieces of software, like web browsers, word processors, computer games, audio video
players, or a Financial Management system.

Features of High-Level languages

a. Third generation Language: High Level Languages are 3rd Generation Languages that
are majorly refinement to the 2nd generation languages.
b. Understandability: programs written in High-level language is easily understood
c. Debugging: Errors can be easily located in theses languages because of the presence of
standard error handling features.
d. Portability: programs written on one computer architecture can run on another computer.
This also means that they are machine independent.
e. Easy to Use: Since they are written in English like statements, they are easy to use.
f. Problem-oriented Languages: High level languages are problem oriented such that they
can be used for specific problems to be solved.
g. Easy Maintenance: We can easily maintain the programs written in these languages.
h. Translator Required: There is always a need to translate the high-level language
program to machine language.

Higher Level programming languages

These are fifth Generation Languages (5GLs). Fifth Generation systems (5GSs) are characterized
by large scale parallel processing (many instructions being executed simultaneously), different
memory organizations, and novel hardware operations predominantly designed for symbol
manipulation. Popular example of 5GL is prolog. These type of languages requires design of
interface between human being and computer to permit affective use of natural language and
images.
Translator used by Programming Languages
Programming languages are artificial languages and they use translators for the computer system
to convert them to usable forms. There are three levels of programming languages: They are

8
Machine Language (ML), Low Level Language (al known as Assembly Language) and High
Level Language. The translators used by these languages differ and they have been classified
into: Compiler, Interpreter or Assembler. Machine Language does not use translator.

Low level language uses a translator called Assembler. An Assembler converts program
written in Low Level Language (Assembly Lang) to machine code. High Level Language uses
compiler, interpreter or both. Our emphasis in this course is on some selected High Level
Languages (HLL). Some examples of HLL include C, C++, Delphi, PASCAL, FORTRAN,
Scala, Python, PERL, Delphi, QBASIC and so on. The language that may be considered mostly
are: C, Java, Python and VBscript.

General Comments on Some High Level Programming Languages


i. C is a compiled procedural, imperative programming language made popular as the basis
of Unix. The language is very popular and is found useful in building OS, mathematical
and scientific applications.
ii. C++ is a compiled programming language that is based on C, with support for object-
oriented programming. It is one of the most widely-used programming languages
currently available. It is often considered to be the industry-standard language of game
development, but is also very often used to write other types of computer software
applications.
iii. C# is an object-oriented programming language developed by Microsoft as part of their
.NET initiative and later approved as a standard by European Computer Manufacturers
Association (ECMA) and International Organization for Standardization (ISO).

C# has a procedural, object oriented syntax based on C++ that includes aspects of several
other programming languages (most notably Delphi, Visual Basic, and Java) with a
particular emphasis on simplification.
iv. FORTRAN is a general-purpose, procedural, imperative programming language that is
especially suited to numeric computation and scientific computing. Originally developed
by International Business Machines corporation (IBM) in the 1950s for scientific and
engineering applications. FORTRAN has come in different versions over the years. We
have FORTRAN II, FORTRAN 98 and so on.
v. VBScript (Visual Basic Script) is developed by Microsoft with the intention of

9
developing dynamic web pages. It is client-side scripting language like JavaScript.
VBScript is a light version of Microsoft Visual Basic. The syntax of VBScript is very
similar to that of Visual Basic. The light language allows you to make your webpage to
be more lively and interactive, then you can incorporate VBScript in your code.
vi. Java is an object oriented interpreted programming language. It has gained popularity in
the past years for its ability to be run on many platforms, including Microsoft Windows,
Linux, Mac OS, and other systems. It was developed by Sun Microsystems.
vii. Pascal is a general-purpose structured language named after the famous mathematician
and philosopher Blaise Pascal.
viii. BASIC (Beginner's All purpose Symbolic Instruction Code) was mostly used when
microcomputers first hit the market, in the 1970s. Later, it largely replaced by other
languages such as C, Pascal and Java. Whilst some commercial applications have been
written in BASIC it has typically been seen as a language for learning/teaching
programming rather than as a language for serious development.
ix. PHP (Hypertext Preprocessor)is a programming language with focus on web design and a
C-like syntax.

Programming Language Paradigm


Different programming languages support different styles of programming approach (called
programming paradigms). Part of the skill that a programmer should be well grounded in is
selecting a programming language or combination of languages that is best suited for the task at
hand. Different programming languages require different levels of detail to be handled by the
programmer when implementing algorithms, often in a compromise between ease of use and
performance. Programming paradigms are a way to classify programming languages based on
their features. A particular language can be classified into multiple paradigms. Some
programming paradigms are concerned mainly with implications for the execution model of the
language, such as allowing side effects and whether the sequence of operations is defined by the
execution model. Other paradigms are concerned mainly with the way code is organized. Either
by grouping code into units along with the state that is modified by the code. Lastly, others are
concerned mainly with the style of syntax and grammar.
Types of programming paradigms
1) Imperative language
2) Functional language
10
3) Object-oriented language
4) Concurrent languages
5) Logic programming language
6) Scripting programming language.

Note: It is important to point out that some programming languages support multiple paradigms.
For instance, Python and Java are in this category. These two languages are predominantly object
oriented in nature but they have support for some other programming paradigms to some extent.
Python is a High Level Programming Language that supports imperative, object oriented and
functional programming paradigms.

1. Imperative Languages

Imperative programming is called so because it is based on commands that update variables held
in storage. In the 1950s, the first programming language designers recognized that variables and
assignment commands constitute a simple but useful abstraction from the memory fetch and
update of computers' instruction sets. This close relationship with computer architecture has
largely led to efficient implementation. Languages that fall into the imperative paradigm have
two main features: they state the order in which operations occur, with constructs that explicitly
control that order and they allow side effects. In which state can be modified at one point in time,
within one unit of code, and then later read at a different point in time inside a different unit of
code. The communication between the units of code in an imperative language is not explicit.
The key concepts of imperative programming languages are

i. Variables
ii. Commands
iii. Procedures
iv. Data abstraction.

11
Examples of languages in this category include: FORTRAN (FORTRAN 77, FORTRAN 98),
ALGOL (ALGOL 58, ALGOL 60), C, ADA and so on.

2. Functional Programming Languages

The model of computation in functional programming languages is the application of functions


to arguments. The key concepts of functional programming are:
i. Expressions are key concept of functional programming because their purpose is to
compute new values from old ones. This is the very essence of functional programming.

ii. Functions are key concept of functional programming because functions abstract over
expressions.
iii. Parametric polymorphism is a key concept of functional programming because it enables
a function to operate on values of a family of types. In practice, many useful functions are
naturally polymorphic, and parametric polymorphism greatly magnifies the power and
expressiveness of a functional language.
iv. Data abstraction is a key concept in the more modern functional languages such as Meta
Language (ML) and HASKELL. Data abstraction supports separation of important issues,
which is essential for the design and implementation of large programs.
v. Lazy evaluation is based on the simple notion that an expression whose value is never
used need never be evaluated.

3. Object Oriented Programming Languages

In object-oriented programming, OOP, a program code is organized into objects that contain
state that is only modified by the code that is part of the object. Most object-oriented languages

12
are also imperative languages to some extent. Examples of these languages include: Java, C++,
Python, Smalltalk, C# and a host of others. The key concepts of OOP are

i. Objects
ii. Classes
iii. Subclasses
iv. Inheritance
v. Inclusion polymorphism.

Object Oriented Programming has been widely accepted in the computing world because objects
give a very natural way to model both real-world and cyber-world entities. Classes and class
hierarchies lead to highly suitable as well as reusable units for constructing large programs.
Object-oriented programming fits well with object-oriented analysis and design and hence
supports these development of large software systems.

4. Concurrent Programming Languages

A concurrent programming language is defined as one which uses the concept of simultaneously
executing processes or threads of execution as a means of structuring a program. Concurrent
programming allows the execution of commands to be overlapped, either by an arbitrary
interleaving execution called multiprogramming or by simultaneous execution on multiple CPUs
called multiprocessing. The key concepts of concurrent programming are

i. Parallel execution of two or more processes: parallel execution is the essential difference
between sequential and concurrent programming. Once we allow the ordering of events
in the execution of a program to be weaker than total ordering, it leads to consequences
such as (i) the possibility that update operations on variables might fail to produce valid
results, and (ii) the loss of determinism. These issues amplify each other, and have the
potential for complete chaos.
ii. Inter-process synchronization: synchronization enables the programmer to ensure that
processes interact with each other in an orderly manner, despite these difficulties. Lapses
13
of synchronization are usually disastrous, causing sporadic and irreproducible failures.
iii. synchronized access to shared data by inter-process mutual exclusion: mutual exclusion
of access to shared variables restores the semantics of variable access and update. This is
achieved by synchronization operations allowing only one process to access a shared
variable at any time. These operations are costly, and must be applied with total
consistency. It is therefore desirable for high-level concurrent programming languages to
offer a reliable, compiler-implemented means of mutual exclusion.
iv. synchronized transfer of data by inter-process communication: communication provides a
more general form of interaction between processes, because it applies as well in
distributed systems as in centralized systems. Some concurrent programming languages
such as CSP (Communicating Sequential Processes) and OCCAM have been based
entirely on communication and avoiding shared variables and their problems. Concurrent
programming paradigms based on communication might dominate in the future if CPU
technology continues to outstrip storage technology. This will ensure that accessing a
variable becomes, for all practical purposes, an exercise in data communication. Until
then shared data will continue to be preferred, because it capitalizes on and extends a
conceptual model.
v. Concurrent control abstractions: concurrent control abstractions promote reliable
concurrent programming by taking much of the burden of synchronization into the
programming language.

14
5. Logic Programming

A logic program implements a relation. Since relations are more general than mappings,
logic programming is potentially higher-level than imperative or functional programming.
The key concepts of logic programming are therefore:

i. Assertions
ii. Horn clauses
iii. Relations
Prolog is an example of a programming language that follows the Logic paradigm.
PROLOG's primitive values are numbers and atoms. Atoms can be compared with one
another, but have no other properties. They are used to represent real-world objects that are
primitive.

15
6. Scripting Programming Languages

A software system often consists of a number of subsystems controlled or connected by a


script. Therefore, a script is used to glue subsystems together. One example of gluing is a
system designed to create a new user account on a computer but also consist of a script that
calls programs to perform the necessary system administration actions. Another example is a
system that enables a user to fill a Web form, converts the form data into a database query,
transmits the
query to a database server, converts the query results into a dynamic Web page, and
downloads the latter to the user's computer for display by the Web browser. In the examples
given, each subsystem could be a complete program designed to stand alone, or it could be a
program unit designed to be part of a larger system, or it could be itself a script. Each
subsystem could be written in a different programming or scripting language. Scripting is
similar to imperative programming because scripting languages support variables,
commands, and procedures. The key concept includes
High-level string processing: All scripting languages provide very high-level support for
string processing. The ubiquitous nature of textual data such as e-mail messages, database
queries and results and HTML documents necessitated the need for High-level string
processing. High-level graphical user interface support: High-level support for building
graphical user interfaces (GUIs) is vital to ensure loose coupling between the GUI and the
application code. This is imperative because GUI can evolve rapidly as usability problems
are exposed.

Dynamic typing: Many scripting languages are dynamically typed. Scripts must be able to
pass data to and from subsystem written in different languages when used as glue. Scripts
often process heterogeneous data, whether in forms, databases, spreadsheets, or Web pages.
Basic Add, Subtract, Multiplication and Division Script ' Define a function to divide two numbers
Function Divide(x, y)
VBScript
If y = 0 Then
' Define a function to add two numbers Divide = "Error: Division by zero!"
Else
Function Add(x, y)
Divide = x / y
Add = x + y End If
End Function
End Function
' Main script
' Define a function to subtract two numbers Dim num1, num2
num1 = 10
Function Subtract(x, y)
num2 = 2
Subtract = x - y
[Link] "Addition: " & Add(num1, num2)
End Function
' Define a function to multiply two numbers [Link] "Subtraction: " & Subtract(num1, num2)

Function Multiply(x, y) [Link] "Multiplication: " & Multiply(num1, num2)


Multiply = x * y 16 [Link] "Division: " & Divide(num1, num2).
End Function
To run save as [Link]

1 2
B: LANGUAGE DESIGN AND PROGRAM TRANSLATION

Language Definition Structure


While programming as a beginner programmer, you are expected to have a real picture of
how you want your program to look like or probably how it should behave/work after
compilation.

It is important for every programmer to have an understanding of programming language


definition structure.

Grammars
In Formal Language, a grammar is a set of production rules for strings in the language. The
rules describe how to form strings from the language alphabets that are valued according to
system. It is a grammar that consists of finite set of production rules.

Formal language is an important topic area in the study of programming languages. Every
programming language has its set of grammar that should be well defined while building the
language translator (compiler in particular). This material will only mention some of the key
areas that students will be taught and introduced to. Some of the terms that students should
master in this section are: Grammar, Compiler, Production rule, Program Syntax (or syntax),
symbol table, parsing, terminal symbol. Non-terminal symbol, parse tree, syntax violation
and so on.

A parse tree is also known as derivation tree. This is defined as an ordered, rooted tree that
represents the syntactic structure of a string according to some context free grammar. Parse
tree is a concept that has to be understood in the context of Compiler Construction. This tree
shows the procedure that every compiler uses to parse program statements in a program
being fed into it.

Grammar

A grammar enables us to transform a program, which is normally represented as a linear


sequence of ASCII characters, into a syntax tree. Only programs that are syntactically valid
can be transformed in this way. This tree will be the main data-structure that a compiler or
interpreter uses to process the program. By traversing this tree the compiler can produce
machine code, or can type check the program, for instance, by traversing a tree the

17
interpreter can simulate the execution of the program.

The main notation used to represent grammars is the Backus-Naur Form (BNF). This
notation, invented by John Backus and further improved by Peter Naur, was first used to
describe the syntax of the ALGOL programming language. A BNF grammar is defined by a
four-element tuple represented by (T, N, P, S). The meaning of these elements is as follows:

a. T is a set of tokens. Tokens form the vocabulary of the language and are the smallest
units of syntax. These elements are the symbols that programmers see when they are
typing their code, e.g., the while's, for's, +'s, {'s, etc.
b. N is a set of non-terminals. Non-terminals are not part of the language per se. Rather,
they help to determine the structure of the derivation trees that can be derived from
the grammar. Usually we enclose these symbols in angle brackets (< >), to
distinguish them from the terminals.
c. P is a set of productions rules. Each production is composed of a left-hand side, a
separator and a right-hand side, e.g., <non-terminal> := <expr1> ... <exprN>, where
':=' is the separator. For convenience, productions with the same left-hand side can
be abbreviated using the symbol '|' (alternation or choice operator). The pipe, in this
case, is used to separate different alternatives.
d. S is a start symbol (<S>). Any sequence of derivations that ultimately produces a
grammatically valid program starts from this special non-terminal.

As an example, below we have a very simple grammar that recognizes arithmetic


expressions. In other words, any program in this simple language represents the product or
the sum of names such as 'a', 'b' and 'c'.

<exp> ::= <exp> "+" <exp>


<exp> ::= <exp> "*" <exp>
<exp> ::= "(" <exp> ")"
<exp> ::= "a"
<exp> ::= "b"
<exp> ::= "c"

This grammar could be also represented in a more convenient way using a sequence of bar
symbols, e.g.:

18
<exp> ::= <exp> "+" <exp> | <exp> "*" <exp> | "(" <exp> ")" | "a" | "b" | "c"

Notice that context-free grammars are not the only kind of grammar that computers can use
to recognize languages. In fact, there exist a whole family of formal grammars, which have
been first studied by Noam Chomsky, and today form what we usually call the Chomsky's
hierarchy. Some members of this hierarchy, such as the regular grammars are very simple,
and recognize a relatively small number of languages. Nevertheless, these grammars are still
very useful.

Regular grammars are at the heart of a compiler's lexical analysis, for instance. Other types
of grammars are very powerful. As an example, the unrestricted grammars are as
computationally powerful as the Turing Machines. Nevertheless, in this note we will focus
on context-free grammars, because they are the main tool that a compiler uses to convert a
program into a format that it can easily process.

Operators in C / C++ and Java Programming Language

C Program Operators are the foundation of any programming language. Thus, the
functionality of C/C++ /Java programming language is incomplete without the use of
operators. We can define operators as symbols that helps us to perform specific
mathematical and logical computations on operands. In other words we can say that an
operator operates the operands. For example, consider the below statement:
c = a + b;

Here, „+‟ is the operator known as addition operator and „a‟ and „b‟ are operands. The
addition operator tells the compiler to add both of the operands „a‟ and „b‟. C/C++ has many
built-in operator types and they can be classified as:

 Arithmetic Operators: These are the operators used to perform


arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %, ++, –
). Arithmetic operator are of two types:
1. Unary Operators: Operators that operates or works with a single operand
are unary operators. For example: (++ , –)

2. Binary Operators: Operators that operates or works with two operands

19
are binary operators. For example: (+ , – , * , /).
 Relational Operators: Relational operators are used for comparison of the values of
two operands. For example: checking if one operand is equal to the other operand or
not, an operand is greater than the other operand or not etc. Some of the relational
operators are (==, > , = , <= ). To learn about each of these operators in details go to
this link.
 Logical Operators: Logical Operators are used to combine two or more
conditions/constraints or to complement the evaluation of the original condition in
consideration. The result of the operation of a logical operator is a boolean value
either true or false. To learn about different logical operators in details please visit
this link.

 Bitwise Operators: The Bitwise operators are used to perform bit-level operations
on the operands. The operators are first converted to bit-level and then calculation is
performed on the operands. The mathematical operations such as addition,
subtraction, multiplication etc. can be performed at bit-level for faster processing.
 Assignment Operators: Assignment operators are used to assign value to a variable.
The left side operand of the assignment operator is a variable and right side operand
of the assignment operator is a value. The value on the right side must be of the
same data-type of variable on the left side otherwise the compiler will
raise an error. Different types of assignment operators are as follows:

Assignment operator (equality sign) “=”: This is the simplest assignment


operator. This operator is used to assign the value on the right to the variable
on the left. For example:
a = 10; b = 20; ch = 'y';

Increment and Assignment “+=”: This operator is combination of „+‟ and „=‟
operators. This operator first adds the current value of the variable on left to the
value on right and then assigns the result to the variable on the left. Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 10. Then (a += 20) = 30.

Decrement and Assignment “-=”: This operator is combination of „-„ and „=‟
operators. This operator first subtracts the current value of the variable on left

20
from the value on right and then assigns the result to the variable on the
left.
Example:
(a -= b) can be written as (a = a - b)

If initially value stored in a is 8. Then (a -= 6) = 2.

Multiplication and Assignment “*=”: This operator is combination of „*‟ and


„=‟ operators. This operator first multiplies the current value of the variable on
left to the value on right and then assigns the result to the variable on
the left.

Example:
(a *= b) can be written as (a = a * b)

If initially value stored in a is 4. Then (a *= 7) = 28.

Division and Assignment “/=”: This operator is combination of „/‟ and „=‟
operators. This operator first divides the current value of the variable on left by
the value on right and then assigns the result to the variable on the left.
Example:
(a /= b) can be written as (a = a / b)

If initially value stored in a is 9. Then (a /= 3) = 3.

Examples:
Mathematical operators
Suppose J = 23 and K = 5, find (i) P = J%K, (ii) Q = J/K

Answer
(i) R = J%K
Since the symbol % stands for modulus (remainder). Then, substitute the values of J and K
into the equation
P= J%K meaning, the remainder when J is divided by
K P= 23%5
P=3 since 23 divided by 5 will produce 4 remainder 3.

21
(ii) Q=J/K (Integer division)
Q = 23/5
Q=4
C Programming Language
C Programming Language uses a compiler and is a very powerful structured
programming language.
#include <stdio.h>
int main()
{
/* I am very delighted to be in this prestigious university, because of the knowledge
impacted on every students within the school */

// About my studentship
printf(" I am student of SLUK! \n");

return 0;

The description of the various parts of the above program is as follows:

 The first line of the program #include <stdio.h> is a preprocessor command, which
tells a C compiler to include stdio.h file before going to actual compilation.
 The next line int main() is the main function where the program execution begins.
 The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
 The next line printf(...) is another function available in C which causes the
message " I am student of SLUK! to be displayed on the screen.
 The next line return 0; terminates the main() function and returns the value 0.

C++ Programming Language


C++ is an example of an object oriented programming language.
Class Syntax

22
 Class declaration
 Constructor
 Member variables (data members)
 Member functions (methods)
 Object creation
 Accessing member functions

Class Syntax:
class classname {
Access - Specifier:
Member Variable Declaration;
Member Function Declaration;
}

The structure of a typical C++ program is as below:


#include <iostream>
using namespace std
int main()

/* I am very delighted to be in this prestigious university, because of the knowledge


impacted on every students within the school */

// About my studentship
Cout<< ("I am student of SLUK! \n");

return 0;
}
The C++ programming language allows programmers to separate program-specific data
types through the use of classes. Classes define types of data structures and the functions
that operate on those data structures. Instances of these data types are known as objects and
can contain member variables, constants, member functions, and overloaded operators defined
by the programmer.

23
Java Programming Language

Java is an Object Oriented Language − In Java, everything is an Object. Java can be easily
extended since it is based on the Object model.

Object-oriented programming (OOP) is a programming language model organized around


objects rather than "actions" and data rather than logic. Historically, a program has been
viewed as a logical procedure that takes input data, processes it, and produces output data.
Java is case sensitive. Java is robust and is architecture-neutral. These are some of the
features of Java as a language.
Java uses hybrid software implementation. That is, Java language uses both compiler and
interpreter.
Basic Concepts in OOP Language

 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An object
is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables − Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Structure of a Java program
The structure of a typical Java program is as follows:
//Comment that is used for documenting a Java program
//import statement as may be
needed public class
ProgramExample

public static void main (String args[])


{
Variable declaration

24
Program codes written using Java syntax
}
}
Note: Each single program statement in Java, C or C++ must end with a semi colon.
Each compound statement opens with an open brace and closes with a closing brace
{
Program codes
}

Another example of a simple Java Program that display a message

/* I am very delighted to be in this prestigious university, because of the knowledge


impacted on every students within the school */

// About my studentship

public static void main(String []args) {

public class MyJavaProgram {

[Link]("I am student of SLUK!");


}
}

SECTION C: PROGRAMMING LANGUAGE EVALUATION

Programming languages differ in various ways. However, a good understanding of some of


the features in a programming language can be of use. Some of the factors that may
influence the choice of a programming language by a programmer include:
i. Programmer experience. This is basically the level of technical-know-how of the
programmer
ii. Ease of Development and Maintenance (Simplicity)
iii. Suitability of the programming language for the problem
iv. Readability.
v. Error Checking

25
vi. Reliability
vii. Portability- This feature allows the programmer to program to run on many
different platforms, with minimal rewriting.
viii. Efficiency- The compiler should be fast. The code itself should be fast.
ix. Low Learning Curve- The language should be easy to learn.
x. Reusability- Writing software components once is cheaper than writing them twice.
xi. Pedagogical value-The language should support and enforce the concepts you
want to teach.
xii. Writeability- This criterion describes to the programmer to say what you mean,
without excessive verbiage.
xiii. Orthogonality- The language should support the combination of its concepts/features
in a meaningful way.
xiv. Consistency- The language should not include needless inconsistencies.
xv. Expressiveness- The programmer should be able to express their algorithm naturally.
xvi. Abstraction- The language should support a high level of data and control abstraction.

Data Types in Programming Languages

Programming languages have support for different data types. This is why they are able to
handle input values to be supplied by the users of programs developed using such languages.
Some programming languages categorize the kinds of data they handle into: Simple and
Composite data.
The simple data types are generally termed primitives. The data types supported by
programming languages differ in different forms.
For example, C programming language has the following examples of data as being
supported: Simple: integer, long integer, short integer, float, double, character, Boolean and
so on. While the composite data types include: List, Structure, Array, and String.
The various data types are used to specify and handle the kind of data to be used in
programming problem. These data types are declared in a programming problem through a
process called variable declaration.

Variable Declaration in Languages


There are various kinds of programming languages. Some languages do not require that
variables are declared in a program before being used while some require that variables are
declared. We can therefore have implicit and explicit variable declaration. Variables can also

26
be classified as global or local, depending on the level of access from within the program.
Implicit Variable Declaration
That is, in Implicit Variable Declaration programming languages in which the variables to
be used in a program may not be declared are said to support implicit variable declaration. A
good example of programming language that supports this variable declaration type is
Python. That is, in Python, a programmer may declare or choose not to declare the variable
that he intends using in a programming language. Example of implicit variable declaration
using C# programming language.

var message = "I am a student of SLUK!"; // The compiler infers that 'message' is a
string

Explicit Variable Declaration


Programming languages in which the variables to be used in a program should be declared
are said to support Explicit variable declaration. Examples of such languages that support
explicit variable declaration are: Java, C, C++, PASCAL, FORTRAN, and many others.
Example of explicit variable declaration using C# programming language.

string name = "Bello"; // Explicitly declaring 'name' as a string


int age = 24; // Explicitly declaring 'age' as an integer

It is important for a programmer to always declare variable before using them in languages
like C, C++, VBscript and Java. Depending on the data type to be used in a program,
examples of variable declaration some selected languages are as below:

Variable Declaration in C Programming Language


int num1, num2, result;

float score1, score2, score3;

double x1, x2 ,x3 ,x4, total;

bool x, y;
Variable Declaration in C++ Programming Language
int num1,num2,result;

27
float score1, score2, score3;

double x1, x2, x3, x4, total;

bool x, y;
Variable Declaration in Java Programming Language

int num1, num2, result;

float score1, score2, score3;


double x1, x2, x3, x4, total;

bool x, y;

Feature Implicit Variable Explicit Variable


Type Declaration Not required Required
Compiler
Inference Compiler determines the type Programmer specifies the type
More explicit and often easier to
Readability Can be less clear, especially for complex expressions understand
Changes in assigned values might lead to unexpected
Maintainability type changes More robust to code changes

Global variable
A Global variable is the kind of variable that is accessible from other classes outside the
program or class in which it is declared. Different programming languages have several
ways in which global variables are being declared, when the need arises.

global_var = 22 # Global variable

def my_function(): {

print(global_var)} # Accessing global variable within a function

my_function(){ # Output: 22

print(global_var) } # Accessing global variable outside a function.

Local Variable
A local variable is the kind of variable that is not accessible from other classes outside the
program or class in which it is declared. These are variables that are used within the current
program unit (or function). In global variables - variables are available to all the program's

28
functions. Using python programming language example.

def my_function(): {
local_var = 13 # Local variable
print(local_var) }
my_function() { # Output: 13
print(local_var) } # This would result in an error as local_var is not accessible
outside the function.

Feature Global Variable Local Variable


Accessible only within the function where it's
Scope Accessible throughout the program declared
Exists throughout the program's
Lifetime execution Exists only during the function's execution
Modification within a
function Requires the global keyword Can be modified directly

The Basic data types associated with variables in languages such as C and Java. These
include the following:

1. int - integer: a whole number.


2. float - floating point value: i.e. a number with a fractional part.
3. double - a double-precision floating point value.
4. char - a single character.
5. Byte- eight (8) bits
6. void - valueless special purpose type.

Note: In C++ and Java, the modifiers or specifiers are used to indicate whether a variable is
global or local.

Data Structures in Java


It has earlier being pointed out that Java has a wide range of data structures.

The data structures provided by the Java utility package are very powerful and perform a
wide range of functions. These data structures consist of the following interface and classes.
 Enumeration (is an interface used to iterate through a collection of objects)

29
 BitSet (is a data structure that represents a sequence of bits (0 or 1))
 Vector (is a legacy class that implements a growable array of objects in [Link] package)
 Stack (is a linear data structure that follows the LIFO principle)
 Dictionary (is typically represented using a map. A map is an object that maps keys to values, where
each key is associated with exactly one value)

 Hashtable (is a data structure in Java that implements the Map interface and stores key-value pairs)
 Properties (is a special type of Hashtable that is used to store key-value pairs where both the
key and value are strings in [Link])

Python Programming Language


Python is another High Level Programming Language that is used for building a wide range
of software solutions (applications). This programming language is fast becoming popular
among data scientists and Machine Learning researchers. The language has support for
procedural and object oriented programming.
Python comes with supports for various data types and has been widely used among
programmers in different domains. In python, the programmer may choose to declare the
variables he wants to use or not. That is, python supports implicit variable declaration unlike
Java that supports explicit variable declaration.

VB Script
Visual Basic Script popularly called VBScript is a scripting language that is used for tying
web interface with its back end. VBscript is used in conjunction with an application interface
called Activex Server Pages (ASP). As a scripting language, the language is very light and
has a set of features that make its use in Web Development a choice for some web
developers. VB Script is a scripting language developed by Microsoft. It is a light version of
Microsoft Visual Basic and the VBScript syntax is very similar to that of Visual Basic.

VBScript Example:
Open your text editor and add the following lines of code.

MsgBox "Welcome to SLUK!"

Type Conversion in Languages


Different programming languages support different kinds of data types. At times in
programming, there may be a need to convert a data from one type to the other. The term
used for describing this process is called Type Conversion. Java and C++ and some other

30
languages are good examples of programming language that support type conversion.

Type Conversion in C
The type conversion process in C is basically converting one type of data type to another to
perform some operation. The conversion is done only between those data types wherein the
conversion is possible e.g. char to int and vice versa.

1) Implicit Type Conversion

This type of conversion is usually performed by the compiler when necessary without any
commands by the user. Thus, it is also called Automatic Type Conversion.

The compiler usually performs this type of conversion when a particular expression contains
more than one data type. In such cases either type promotion or demotion takes place.

Example (1)
int a = 20;
double b = 20.5;
a+b
Conversion will be 20.0, then addition operation will be carried out 20.0+20.5 = 40.5 in
double data type
char ch='a';
int a =13;

a+c
Conversion will be conducted on string „a‟ into integer and will be assigned to c, then addition
operation will be carried out 13+97 = 110 in integer data type

Explicit Type Conversion

Explicit type conversion rules out the use of compiler for converting one data type to another
instead the user explicitly defines within the program the datatype of the operands in the
expression.

The example below illustrates how explicit conversion is done by the user.

Example:
double da = 4.5;

31
double db = 4.6;

double dc = 4.9;

//explicitly defined by user


int result = (int)da + (int)db + (int)dc;

printf("result = %d", result);

Expected Output (When these lines of codes are run in C environment)

Result = 12

Thus, in the above example we find that the output result is 12 because in the result
expression the user has explicitly defined the operands (variables) as integer data type.
Hence, there is no implicit conversion of data type by the compiler.

Type Conversion in Java

When you assign value of one data type to another, the two types might not be compatible
with each other. If the data types are compatible, then Java will perform the conversion
automatically known as Automatic Type Conversion and if not then they need to be casted or
converted explicitly. For example, assigning an int value to a long variable.

Automatic Type Conversion in Java

Widening conversion takes place when two data types are automatically converted. This
happens when:

i. The two data types are compatible.


ii. When we assign value of a smaller data type to a bigger data type.

For example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or Boolean. In addition, char and Boolean
are not compatible with each other.

class Test

32
{

public static void main(String[] args)


{
int i = 100;

// automatic type conversion of integer to long


long l = i; /*The integer value stored in i is automatically converted to a long value and assigned to the l variable. This is called
widening conversion because long has a larger range than int.*\

// automatic type conversion of long to float


float f = l; /*The long value stored in l is automatically converted to a float value and assigned to the f variable. This is also a
widening conversion.*\

[Link]("Int value "+i);


[Link]("Long value "+l);
[Link]("Float value "+f);
}
}
Expected Output
Int value 100
Long value 100
Float value 100.0

Narrowing or Explicit Conversion in Java


If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.

 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.
 Char and number are not compatible with each other. Let‟s see when we try to convert
one into other.

//Java program to illustrate incompatible datatype for explicit type conversion

public class Test


{

public static void main(String[] args)


{

33
char ch = 'c';

int num = 88;

ch = num;
}
}
The above lines of code will result in an error as shown below:
7: error: incompatible types: possible lossy conversion from int to char ch = num;
^
1 error
Explicit Conversion
Explicit conversion, which is also considered as type casting, is a concept where you manually
convert a value from one data type to another. This is often necessary when you need to use a
value in a context that requires a different data type.
Example:

//Java program to illustrate explicit type


conversion
class Test // This defines class named Test (In Java program, all codes must reside within a class)
{

public static void main(String[] args) // This is the main method, the entry point for program execution
{
double d = 100.04; // This declares a variable named d of type double and initializes it with the value 100.04.

//explicit type casting


long l = (long)d; // This performs explicit type casting.
 (long): This is the cast operator, which tells the compiler to convert the value on the right-hand side to the long data type.
 d: The double value 100.04 is being cast to a long. Since long is an integer type, the fractional part (0.04) will be
truncated, resulting in l having the value 100.

//explicit type casting


int i = (int)l; // This performs another explicit type casting.

 (int): This cast operator converts the value of l (which is currently 100) to the int datatype.
 Since l is already an integer, this cast operation does not change the value of i. It will also be 100.

[Link]("Double value "+d); // These lines print the values of d to the console.

//fractional part lost

34
[Link]("Long value "+l); // These lines print the values of l to the console.
//fractional part lost
[Link]("Int value "+i); // These line print the values of i to the console.
}
}
Expected outputs
Double value 100.04
Long value 100
Int value 100

Data loss-When casting from a larger data type (like double) to a smaller one (like long or
int), data loss can occur. In this case, the fractional part of the double value is lost during
the conversion.

//Java program to illustrate Conversion of int and double to


byte class Test
{
public static void main(String args[])
{
byte b; // It declares a variable named b of type byte. It represents a signed 8-bit integer, which can hold values from -128 to
127.

int i = 257; // This declares an integer variable i and initializes it with the value 257.
double d = 323.142; // This declares a double-precision floating-point variable d and initializes it with the value
323.142.

[Link]("Conversion of int to byte."); // Display the characters in quotation to the console.


//i%256
b = (byte)i; // This line performs explicit type casting.
 (byte): This is the cast operator, which tells the compiler to convert the value on the right-hand side to the byte data type.
 i: The integer value 257 is being cast to a byte.
 Important: A byte can only hold values within the range -128 to 127. Since 257 exceed this range, the result of the cast will be the
remainder after dividing 257 by 256 (which is 1).
 Therefore, b will be assigned the value 1.

[Link]("i = " + i + " b = " + b); // This line prints the values of i and b to the console

[Link]("\nConversion of double to byte."); // Display the characters in quotation to the


console

//d%256
b = (byte) d; // This is explicit type casting

35
 This line casts the double value d (323.142) to a byte.
 Similar to the previous cast, the fractional part of d will be discarded.
 Then, the integer part (323) will be reduced modulo 256 (323 % 256 = 67).
 Finally, b will be assigned the value 67.

[Link]("d = " + d + " b= " + b); // This line prints the values of d and b to the console
}
}
Expected Output
Conversion of int to byte.
i = 257 b = 1
Conversion of double to byte.
d = 323.142 b= 67

 Data Loss: When casting from a larger data type (like int or double) to a smaller one (like byte), data loss can occur if the value
exceeds the range of the smaller data type.
 Modulo Operator (%): This operator gives the remainder after division.

Runtime Consideration in Programming Languages


Runtime programming is about being able to specify program logic during application
execution, without going through the code-compile-execute cycle. This note describes key
elements of the infrastructure required to support runtime programming in Java, and presents
a fairly detailed analysis of the design.
Programmers are expected to consider the run time for his choice of implementation in the
chosen programming language.
Binding in Programming Languages
We may have to start this part by asking the question “What is binding in programming
languages?” Recall that a variable is the storage location for the storing of data in a program.
Binding refers to the association of attributes with program entities. Binding can be static or
dynamic. The C and Java are examples of programming languages that support binding.
Dynamic Binding allows greater flexibility but at the expense of readability, efficiency and
reliability.

Demonstration of Binding in C and Java


As an example, let us take a look at the program below, implemented in C. In line 1, we have
defined three names: int, i and x. One of them represents a type while the others represent the
declaration of two variables. The specification of the C language defines the meaning of the
keyword int. The properties related to this specification are bound when the language is
defined. There are other properties that are left out of the language definition. An example of
this is the range of values for the int type. In this way, the implementation of a compiler can

36
choose a particular range for the int type that is the most natural for a specific machine. The
type of variables i and x in the first line is bound at compilation time. In line 4, the program
calls the function do_something whose definition can be in another source file. This
reference is solved at link time.
The linker tries to find the function definition for generating the executable file. At loading
time, just before a program starts running, the memory location for main, do_something, i
and x are bound. Some bindings occur when the program is running, i.e., at runtime. An
example is the possible values attributed to i and x during the execution of the program.

Int i, x=0; //I is loop counter and x stores the accumulated results, which is first initialized as zero
void main() // is the main function where the program execution starts
{
for(i=1; i<=50; i++) //for loop that iterates 50 times
x+= do_something (x); // function named do_something that takes an integer argument (x)
}
 In static binding, the compiler determines which function to call at compile time. This is based on the function's name and the types
of its arguments.

 The code x += do_something(x); involves a function call to do_something(). Since the compiler knows the name and the type of the
argument (x is an integer), it can directly link the call to the specific do_something() function at compile time.

 Function Overloading: If multiple functions with the same name but different argument
types exist, the compiler uses static binding to select the correct function based on the
argument types provided in the function call.

 Early Binding: Static binding is also referred to as early binding because it happens
before the program's execution.
In dynamic binding (also known as late binding), the function to be called is determined at
runtime. This is common in object-oriented languages with polymorphism, where the
actual method to be invoked is decided based on the object's runtime type.
The same implementation can also be done in Java, which is as follows:
Public classExample
{
inti, x=0;
public static void main (String[]args)
{
For (i=1; i<=50; i++)
{
x+=do_something(x);
}

37
}
}

The Java code depicts static binding in the context of function calls.

 In static binding, the compiler determines which function to call at compile time. This is based on the function's name and the
types of its arguments.
 In the line x += do_something(x);, the compiler encounters a function call to do_something(). Since the compiler knows the
name of the function and the type of the argument (x is an integer), it can directly link the call to the specific do_something()
function at compile time.

Initialization as a concept in programming languages


Initialization is the binding of a variable to a value at the time the variable is being bounded
to storage. For instance in Java, C and C++, a variable can be declared and initialized at the
same time as follows
float x1, x2;
int num1, num2, total, avaragevalue;

bool P,R,Q;

Flow Control in Programming Languages


Different programming languages have support for flow control. Flow control constructs
such as if-then-else, while-do, and Do while take as arguments a boolean expression and one
or more action statements. The actions are either flow control constructs or assignment
operations, which can be constructed recursively too. The Java, or C++ class written to
provide an if<condition<then<action-1<else<action-2 construct takes three arguments in its
constructor, a boolean result object and two action objects, each constructed using one or
more primitive constructs. The evaluate() method of the if-then-else class performs the if-
then-else logic upon invocation with appropriate arguments. Most flow control constructs
can be provided in a similar manner.
In programming languages, complex program logic can be constructed as a hierarchy of
objects corresponding to the primitive constructs. Such a conglomerate of objects, each
individually performing a simple task, and cooperating together to achieve a complex one is
the key design principle in this technology and ideally suited for distributed processing.
Other programming languages like C, PASCAL, DELPHI, Python, FORTRAN, Scala
among others have their syntaxes for handling flow control. The flow control structures are
generally used when there is a need to reach some conclusion based on some set of
conditions.

38
Compilation time: The period when the source code (written in a high-level language like
C, Java, Python) is translated into machine code. While Runtime is the period when the
compiled code (or interpreted code in languages like Python) is actually executed by the
computer's processor
Strongly Typed or Weakly Typed Languages
Type checking is another feature of programming languages that students have to be well
familiar with. Under this section, programming languages can either be strongly typed or
weakly typed. A good example of strongly type language is LISP. A good example of
weakly typed language is PHP, C, Perl and JavaScript. However, the program designer
can choose to implement a strict type checking as desired, by checking for type-
compatibility during construction of each of the primitive constructs.

primitive construct refers to the most basic and fundamental building blocks of a
programming language. These are the simplest elements that cannot be further broken down
into smaller components. They provide the foundation upon which more complex
programming structures are built.

Strongly programming language


 Strict Type Enforcement: In strongly typed languages, variables are strictly associated
with a specific data type (e.g., integer, string, boolean).
 Reduced Errors: This strictness helps prevent unintended behavior and reduces the
likelihood of runtime errors caused by type mismatches.
 Examples: Java, C#, Python, Go, Swift.

While weakly programming language


 Loose Type Enforcement: In weakly typed languages, data types can be implicitly
converted or coerced, allowing for more flexibility in how data is handled.
 Potential for Errors: While offering flexibility, this can lead to unexpected behavior and
potential runtime errors if not handled carefully.
 Examples: JavaScript, PHP, Perl
Dynamism of Programming Languages
Dynamic programming language (DPL) is a class of high-level programming languages
which, at runtime, execute many common programming behaviors that static programming
languages perform during compilation. These behaviors could include extension of the
program, by adding new code, by extending objects and definitions, or by modifying the
type system. Although similar behaviours can be emulated in nearly any language, with
varying degrees of difficulty, complexity and performance costs, dynamic languages provide

39
direct tools to make use of them.
Many of these features were first implemented as native features in the Lisp programming
language. Most dynamic languages are also dynamically typed, but not all are.
DPL refers to a specific category that exhibits a high degree of flexibility and adaptability
during runtime. A very good example DPL is python and other PLs

Main Features of DPLs:

1. Dynamic Typing: This is the most prominent feature. Variables in dynamic languages
don't have fixed data types. You can assign a value of one type to a variable and then
reassign it to a value of a different type later on.
2. Late Binding: Function calls and other operations are resolved at runtime rather than
during compilation. This allows for greater flexibility in how objects and methods
interact.
3. Introspection: Dynamic languages often provide powerful introspection capabilities,
allowing you to examine and modify the structure and behavior of objects and code at
runtime.

Runtime of a Program
Runtime is also called execution time. It is the time during which a program is running
(executing), in contrast to other program lifecycle phases such as compile time, link time and
load time. When a program is to be executed, a loader first performs the necessary memory
setup and links the program with any dynamically linked libraries it needs, and then the
execution begins starting from the program's entry point. Some program debugging can only
be performed (or is more efficient or accurate when performed) at runtime. Logic errors and
array bounds checking are examples of such errors in programming language.
Exception Handling in Programming Languages
Exception handling is a language feature designed to handle runtime errors, providing a
structured way to catch completely unexpected situations as well as predictable errors or
unusual results without the amount of inline error checking required of languages without it.
More recent advancements in runtime engines enable automated exception handling which
provides 'root- cause' debug information for every exception of interest and is implemented
independent of the source code, by attaching a special software product to the runtime
engine. When an error occurs in a Java program it results in an exception being thrown. It
can then be handled using various exception handling techniques.
Lexical Analysis and Parsing
In compilation, a High Level Language Program (source language) is translated into
machine code called the object code. Compilation process has several phases. This includes
40
lexical analysis which converts characters in the source program into lexical units
(identifiers, operators and keywords). The other stages are syntactic analysis: This
transforms lexical units into parse trees which represent the syntactic structure of a program.
Semantic Analysis, machine independent code improvement, and target code generation.
Diagrammatically, the representation of compilation process can be as below:

Semantic Analysis
Syntactic Analysis (SA) is one of the stages of compilation. This transforms lexical units
into parse trees which represent the syntactic structure of program. Semantic Analysis
checks for errors that are hard to detect during syntactic analysis and then generate
intermediate code.
It is the task of ensuring that the declarations and statements of a program are semantically
correct. That is the meaning of the statements is clear and consistent with the way in which
control structures and data types are supposed to be used.
Thus, SA is the third phase of Compiler. Semantic Analysis makes sure that declarations and
statements of program are semantically correct. It is a collection of procedures which is
called by parser as and when required by grammar. Both syntax tree of previous phase and
symbol table are used to check the consistency of the given code.

41

Common questions

Powered by AI

Automatic type conversion simplifies coding by allowing implicit conversions between compatible types, especially useful in expressions with mixed data types. Explicit type conversion is crucial when dealing with incompatible types, where specific data handling is required, such as converting larger data types to smaller ones. Automatic conversion enhances ease of use while explicit conversion provides control over data precision and compatibility .

Understanding various programming language constructs enhances a programmer's ability to develop effective algorithms, improve their use of existing languages, increase their vocabulary of programming constructs, and allows them to make better language choices for specific projects. This understanding also facilitates learning and designing new programming languages, contributing to advancements in computing .

Middle-level languages, like C and C++, offer features from both low-level and high-level languages. They provide direct memory access akin to low-level languages while maintaining high-level abstraction benefits such as user-friendliness and the ability to develop complex applications efficiently. This hybrid nature makes them versatile for both system-level and application-level programming .

Programming in machine language is error-prone due to its binary nature, making debugging difficult. It requires substantial knowledge of computer architecture and lacks portability, as programs are specific to a particular machine's architecture. These factors make machine language difficult and inefficient for developing large-scale applications .

Low-level languages are closer to machine code, offering little abstraction, and require a deep understanding of computer architecture, making them difficult to use and error-prone. High-level languages abstract hardware complexity, using syntax similar to human languages, which makes them easier to learn, debug, and maintain. Additionally, high-level languages offer greater portability across different computer systems .

In Java, type conversion is determined by data type compatibility. Automatic or widening conversion occurs when a smaller data type is assigned to a larger one or when types are compatible, enhancing ease of use. Conversely, incompatible types require explicit casting, highlighting the need for developer intervention to ensure correct data handling and prevent data loss .

Ensuring program portability involves making the definitions of the program independent of specific machine features. This requires using high-level languages that allow translation through compilers or interpreters, thus permitting the same code to run on different architectures. The language environment must also support consistent behavior across platforms .

High-level languages have significantly improved software development and maintenance by simplifying syntax and increasing understandability and portability. They offer standard error handling features, making debugging easier, and facilitate maintenance due to their problem-oriented nature. These languages allow developers to focus on logic instead of technical details, speeding up development cycles .

Programming languages evolve over time, incorporating experiences and improvements from older languages, leading to more capable and efficient languages. This evolution is influenced by advancements in computer architecture and software development practices. Such changes enable computers to handle more complex tasks and applications, reflecting progress from early military and scientific usages to diverse modern applications .

Type conversion can impact data integrity when converting from a larger to a smaller data type, leading to data loss, such as truncating fractional parts in numeric conversions. In Java and C, developers must use explicit casting to manage such conversions to prevent unintended data loss. Careful management of conversions ensures integrity by respecting the limitations of each data type .

You might also like