CSC Survey Programming Language
CSC Survey Programming Language
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
SECTION A: HISTORY AND BASIC CONCEPTS IN PROGRAMMING LANGUAGES
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:
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.
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.
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.
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.
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:
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
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.
A good programming language should provide appropriate data structures, operations, control
structures, and a natural syntax for the problem to be solved.
An ideal programming language should allow data structures, data types and operations to be
defined and maintained as self-contained abstractions.
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
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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
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)
1 2
B: LANGUAGE DESIGN AND PROGRAM TRANSLATION
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
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.
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.
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:
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:
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)
Example:
(a *= b) can be written as (a = a * b)
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)
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 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.
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;
}
// 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 − 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
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
}
// About my studentship
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.
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.
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
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:
bool x, y;
Variable Declaration in C++ Programming Language
int num1,num2,result;
27
float score1, score2, score3;
bool x, y;
Variable Declaration in Java Programming Language
bool x, y;
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.
def my_function(): {
my_function(){ # Output: 22
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.
The Basic data types associated with variables in languages such as C and Java. These
include the following:
Note: In C++ and Java, the modifiers or specifiers are used to indicate whether a variable is
global or local.
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])
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.
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.
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 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;
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.
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.
Widening conversion takes place when two data types are automatically converted. This
happens when:
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
{
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.
33
char ch = 'c';
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:
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.
(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.
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.
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]("i = " + i + " b = " + b); // This line prints the values of i and b 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.
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.
bool P,R,Q;
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.
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
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
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 .