Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

1

ORGANISATION OF

PROGRAMMING LANGUAGES

SYNTAX

SEMANTICS

SCOPE

BINDING

DATA TYPES

AJAYI Olusola Olajide, PhD


OND, B.SC., M.SC., PhD
MACM, MIEEE, MPSF, MCSTA, MIACSIT, MMCS
(Senior Lecturer, CSC Dept., AAUA)
olusola.ajayi@aaua.edu.ng
ajayicomputer@gmail.com
ajayiprogrammer@gmail.com

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


2

LECTURE OUTLINE

 PROGRAMMING LANGUAGES

 PROGRAMMING PARADIGMS

 PROGRAMMING LANGUAGES: STRUCTURE

 PROGRAMMING LANGUAGES: SYNTAX, SEMANTICS &

SCOPE

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


3

CHAPTER ONE

PROGRAMMING LANGUAGES

1.1 Programming & Programming Languages

1.1.1 What is Programming?

Programming can be viewed as an act of coding solution for a problem. It can also be defined as

an act of giving instruction to the computer to carry out a task.

It simply implies the ability of a programmer to communicate with the computer system in a

particular programming language.

It is a transformational act that brings about changes in the status of task – e.g. manual task to

computational one.

1.1.2 Programming Languages

These indicate the language of choice for which the programmer communicates with the computer

machine. In other words, programming language refers to the language with which a programmer

codes. This can also be said to be mean the nature of tune/language with which a programmer

expresses his/her needs/solution to a problem, to the computer machine to solve a particular and

pertinent problem.

1.1.3 Advanced Definitions

– Programming language refers to syntax or notation with which a programmer

codes/communicate with the computer.

– Programming language is a notation that expresses certain algorithm to be executed

by the computer.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


4

1.1.4 Programming Languages - Types

We have 3 types:

 Machine Language

 Low-Level Language

 High Level Language

Machine Language (ML)

This refers to the language which the computer understands. It is a language in which all

codes/instructions are represented in the form of 0s and 1s.

Low-Level Language (LLL)

This language is very much close to machine language. It needs little translator to real machine

language. It is regarded as SYMBOLIC Language. A good and common example is the

ASSEMBLY Language.

High-Level Language (HLL)

This is a language that is close to normal human English Language. It isn’t a languages the

computer understands, rather it needs the help of an interpreter or a compiler before computer

could understand it. Examples here includes QBasic (Quick – Beginners’ All Purpose Symbolic

and Instruction Code), Fortran (FORmulaTRANslator), Pascal (Delphi), Java, C, C++, C#, Python,

Ada, Eiffel, PHP (Hypertext PreProcessor), COBOL etc.

1.1.5 Programming Languages: Historical Perspective

In the early days of programming, there were no high-level languages. You had to write your

code at the machine or assembly language level. This means that you needed a lot of knowledge

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


5

of the underlying machine and there was no real abstraction over the work that the processor was

doing. This led to a number of problems.

 There was no separation of data and code. In fact your code could easily overwrite the

program as it was executing.

 Control structures were simple goto statements. In a complex program, it was difficult to

understand how a program ended up getting where it was.

 Data could be changed by any part of the program. When debugging a program with

incorrect data, it was very difficult to figure out where that data may have been changed.

I like to summarize these three large problems with simple questions.

List of Problems

1. Where is my data?

2. How did I get here?

3. Who changed the data?

As we walk through subsequent generations of programming languages, let’s discuss how these

problems were addressed by each generation.

The First High Level Languages

The first high level languages were utilitarian languages like Fortran and COBOL. They were

designed to solve math or business problems. They were a huge leap forward in that they

abstracted the programmer from the machine they were writing for. Writing in a high level

English-like language made it easier for programmers to focus on the problem being solved

rather than the details of the computer.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


6

Looking at the LIST OF PROBLEMS listed earlier (previous page – 3 of them), the biggest

advance with these languages was their ability to separate data from code. With the ability

to name variables and the addition of rudimentary support for arrays and records, the

programmer was able to more easily see their data and visualize it in a way that made more sense

in the domain of their problem.

As far as the other two problems are concerned, we still did not make much progress. Control

structures were will largely simple comparisons and goto statements. Data was also largely

global, so understanding who changed something was still a huge challenge.

So with these advances, our big three problem scorecard looks like this.

List of Problems

1. Where is my data? (solved)

2. How did I get here?

3. Who changed the data?

Next Generation Languages

In the years following the development of these initial languages, we got a new generation of

languages like Pascal, PL/I and eventually C. While there were many advances that came with

these languages, the significant of these advances were related to their more advanced control

structures and use of subroutines and functions.

Instead of the basic goto-type control structures, these languages gave us more advanced

for-loops, while-loops and other more expressive control structures. This meant that instead

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


7

of having to trace your program execution through a spaghetti-like sequence of conditionals and

goto statements, you could read the code and start to infer the intent of the programmer.

In addition, these languages moved beyond the rudimentary call and return statements of the

previous generation of languages and gave us more expressive subroutines and functions as ways

to execute repeated code.

These advances largely solved the problem of how did we get here. If you are keeping score,

we now have solved two of the “big three” problems.

List of Problems

1. Where is my data? (solved)

2. How did I get here? (solved)

3. Who changed the data?

Object Oriented Programming

Even with the two phases advances/advancement recorded so far, as programs became

larger, they were still incredibly difficult to debug. This was largely due to our difficulty in

understanding how data was getting changed. With these procedural languages, it was still

possible for any bit of code to modify virtually any data. While there was some ability to use

local variables inside subroutines or functions, most data was either passed around or globally

modified by multiple parts of the program. In the end we now had a spaghetti-like structure to

our data that was almost as painful as the control structure problem we had solved a generation

ago.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


8

The answer to this crisis is the INTRODUCTION of OBJECT ORIENTED

PROGRAMMING PARADIGM – where programmers were able to break codes into

smaller, self-contained “objects” and tightly control how those objects cold be modified.

An object is a collection of data and a set of functions (commonly called methods) that could be

used to access or change that object’s data. Data could not be changed in any other way. We now

had programs made up of many smaller objects with very controlled ways of changing

data. We could now know with absolute assurance who changed the data. It looks like we

had reached Nirvana. If you are keeping score, here we are.

List of Problems

1. Where is my data? (solved)

2. How did I get here? (solved)

3. Who changed the data? (solved)

All solved now! Great!!

Under Chapter Exercise (UCE) I

Student’s Name: _______________________________________________________________

Level: _________________ Matric No: ______________________________________

Questions

(1) Assuming you are dealing with a layman, discuss the term: ‘PROGRAMMING’

(2) Historically, describe the journey of programming languages.

(3) Justify the need for High Level Language as a type of Language.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


9

CHAPTER TWO

PROGRAMMING PARADIGMS

2.1 Programming Paradigms

Programming Paradigms imply trend & evolution of programming languages. It can also described

in the following ways:

i. Refers to trend and development of different programming languages.

ii. It also implies the structure of the various programming languages available.

iii. Due to (ii above), it can be seen as the classification of programming languages

according to their peculiar features.

Programming Paradigms can be captured under the following under-listed programming

paradigms.

IMPERATIVE PROGRAMMING PARADIGM

This is the type of programming that deals with scientific computation i.e. It is found useful in

handling mathematical computation. In this programming language, assignment, sequence and

control statement are very important.

Imperative refers to a programming paradigm that expresses computation by describing its control

flow. This can also be seen as a type of paradigm that emphasis on the possibility of causing

changes in program flow and execution. Imperative, undoubtedly one of the oldest paradigm, is

suitable for handling large and complex mathematical problems.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


10

Examples of this programming paradigm are: FORTRAN, COBOL ,C / C++ and PASCAL

Major Characteristics/Strengths include:

i. Learnability

ii. Legibility

iii. Readability

Major Setbacks/Weakness include:

i. Optimization problem

ii. Error prone

OBJECT ORIENTED PROGRAMMING (OOP) PARADIGM

This is a type of programming in which object interact by sending messages that change their state.

In this programming type, inheritance, polymorphism and object modeling are essential element.

Object-Oriented Programming Paradigm refers to a programming paradigm that emphasis on

object-interaction in form/by way of message parsing. OOP paradigm as the name suggests, deals

with programming with objects, which possesses both data and method (codes). Unlike

Declarative paradigm (Logic and Functional paradigm) that emphasizes function and logic behind

program, OOP paradigm structures program around data & object.

Examples of programming languages in this paradigm include: C++, JAVA, SMALLTALK,

EIFFEL, PHP & VISUAL BASIC.NET

Major Characteristics/Strengths include:

i. Encapsulation

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


11

ii. Inheritance

iii. Polymorphism

Major Setbacks/Weaknesses include:

i. Complexity

ii. Size

iii. Slower/Speed

FUNCTIONAL PROGRAMMING PARADIGM

This programming paradigms deals with mathematical functions in which the domain serves as

the input and the range serves as the output.

Example of this programming paradigm includes: LISP, SCHEME, HASKEL, MIRANDA,

MAPLE, MATHEMATICA and MATLAB.

LOGIC / DECLARATIVE PROGRAMMING PARADIGM

This programming paradigms deal with collection of logical declaration about what outcome a

function should accomplish.

Example of this paradigm includes: PROLOG, SEQUEL, SQL and RPG

Note however, that, merger of both Functional and Logic Paradigm is refer to as Declarative

Programming Paradigm.

Declarative Programming Paradigm refers to a programming paradigm that expresses the logical

aspect of computation. It is the opposite of imperative programming paradigm. Declarative as the

name sounds, describes only the solution to be accomplished without ‘revealing/talking’ about the

implementation. It exists in 2s: Logic and Functional Paradigms

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


12

i. Examples include (LOGIC paradigm): SQL, Prolog, RPG etc.

ii. Examples include (FUNCTIONAL paradigm): MATLAB, R, LISP, MAPLE,


MATHEMATICA etc.

Major Characteristics/Strengths include:

i. Brevity/Briefness & Efficiency

ii. Processing Power & Speed

iii. Easy optimization

Major Setback/Weakness include:

i. Hard to learn

ii. Modelling challenge

EVENT-DRIVEN PROGRAMMING PARADIGM

This programming paradigms deals with design of program that respond to unpredictable events.

These event are normally generated from users’ actions e.g. mouse click, key press.

Example of this paradigm includes: VISUAL BASIC, VISUAL BASIC.NET, VISUAL C++,

VISUAL C#, & JAVA

CONCURRENT PROGRAMMING PARADIGM

This programming paradigm deals with collection of cooperating process by sharing resources

(information) but operating asynchronously.

Example of programming languages in this group include: LINDA, CONCURRENT PASCAL

(DELPHI), HIGH PERFORMANCE FORTRAN and JAVA

2.2 Programming Language Application Domains

These include:

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


13

• Scientific Programming (SP)

• Management information system (MIS)

• Artificial Intelligence (AI)

• System Programming (SP)

• Web-centric Programming (WP)


Programming Language Application Domains…

SCIENTIFIC PROGRAMMING: This is programming language that is used for handling

complex computations. They are also very useful for teaching and learning. Example of this

programming language includes: FORTRAN, COBOL, PASCAL, C and BASIC

NOTE: Scientific programming falls under imperative programming paradigm

MANAGEMENT INFORMATION SYSTEM: This are program that are used for handling

organization information system e.g. payroll system, accounting system, inventory system, online

sale & marketing system. Example of this programming language includes: SQL, COBOL & RPG.

NOTE: MIS falls under logic / declarative programming paradigm

ARTIFICIAL INTELLIGENCE: This are programming types that are used to develop software

that model after human intelligent behavior e.g. robot. Example of this programming language

includes: LISP, PROLOG, MATLAB and SCHEME.

NOTE: AI falls under programming language paradigm of functional and logic programming

language.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


14

SYSTEM PROGRAMMING: This is a programming type which assist in the design and

development of software on which other software runs i.e. system programming deals with

developing software that act as platform on which other programs runs.

Examples are OS SOFTWARE, NETWORK SOFTWARE, INTERPRETER AND COMPILER.

A Common example of programming language use is C.

NOTE: SP falls under imperative programming language paradigm.

WEB-CENTRIC: This programming type involves developing programs that run on the internet.

Web-centric programming is like a two-edged sword, as it derives from both OOP and Event-

driven programming paradigm.

Programming languages used include: JAVA, VISUAL BASIC, VISUAL BASIC.NET, PHP,

HTML, JAVASCRIPT and C++ etc.

Web-Centric falls under OOP and Event-Driven Paradigms

Under Chapter Exercise (UCE) II

Student’s Name: _______________________________________________________________

Level: _________________ Matric No: ______________________________________

Questions

(1) What do you understand by: ‘Programming Paradigms’?

(2) Discuss the various programming paradigms.

(3) Differentiate between Imperative paradigm and object-oriented paradigm.

(4) Distinguish between Event-Driven paradigm and Concurrent paradigm.

(5) With appropriate examples, discuss the various programming languages application

domain/area.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


15

CHAPTER THREE
PROGRAMMING LANGUAGES: STRUCTURE
• THE STRUCTURE OF C#
• C# language like C, comprises majorly of three (3) parts. These are:
- Program header (library, class & method definitions)
- Declaration section (variables & their data types)
- Program Statement (contents of the method) (Simple/Compound, enclosed in brace(s))
• THE STRUCTURE OF C#…
• Program header (library, class & method definitions: watch out for the 3 of them)
Using System; //library definition…for now, others later
namespace shoprog //similar to that of C++, remember?

class myfirstprog //class definition


{
public static void main (string[] args //method definition //java re-echoed?
…….declarations…….
……..code goes here!
}
• THE STRUCTURE OF C#…
• Declaration Section
To discuss and demonstrate declarations in C#, we’ll first discuss DATA TYPES in C#.
• THE STRUCTURE OF C#…
• DATA TYPES
We have:
i. var: This is a generic type. It assumes a type for a variable based on the data
content at run-time (e.g. the value stored into the variables). Though not a
good practice, it definitely has its +side.
For instance, indicating 67 for a variable implies an integer variable, while
supplying 43.21 implies a real variable.
• Other data types are:

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


16

i. integers: This is used for capturing non-decimal values. We have: sbyte, byte,
short, ushort, int, uint, long, ulong
ii. Real (with decimal precision): Here we have: decimal
iii. Real (floating point): Here we have: float, double(a float with greater
precision)
iv. Character (single): char (e.g. char gender;)
v. Character (multiple): string (e.g. string myname; OR string tell_me=“who are
u”;)
vi. Boolean: bool (e.g. bool marital status; OR bool maritalstatus = false;)
vii. Object Type: object
• COMMON I/O STATEMENTS
Logically, we’ll reverse-start this section by first going through the OUTPUT Statement,
rather than starting with the INPUT Statement. (Permit me to do this!) – Thanks! (So, come
to the next slide…)
• OUTPUT STATEMENTS
C# made use of the WRITE Statement (with variants) for outputting to the console/screen.
We have (majorly):
*WRITE: For outputting literals alongside values of variables with immediate
positioning of the cursor without jumping to d next line.
*WRITELINE: Does the same as WRITE with auto-jump capability to the next line.
NB: These are used along with the keyword: CONSOLE
• OUTPUT STATEMENTS cont’d (illustrating…from the previous structure point)
Using System;
namespace shoprog
class myfirstprog
{
public static void main (string[] args)
Console.WriteLine (“Let me see your face Mr. C#”);
}
???Noticed the screen disappears so quickly that you can’t see/view the content? If Yes, then
append/modify ur code
Using System;
namespace shoprog
ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.
17

class myfirstprog
{
public static void main (string[] args)
Console.WriteLine (“Let me see your face Mr. C#”);
Console.ReadKey() //the modification that holds the screen
}
• INPUT STATEMENTS
While READKEY is basically used for returning a Function Key (e.g. for holding on to the
console/screen or responding to keypress e.g RETURN Key, ESC or TAB key etc.), C# made
use of the READLINE Statement for capturing values/data for variables.
e.g. Console.ReadLine ();
• INPUT STATEMENTS (illustrating with the initial example with modification):
Using System;
namespace shoprog
class myfirstprog
{
public static void main (string[] args)
int mynum;
Console.Write (“Indicate the value of the variable: ”);
//3 modifications up there: (i) declaration of a variable names ‘mynum’ (ii) write is used to ensure
the cursor is positioned in front of the literals so as to have the data captured in the same line. (iii)
the literal used is as it relates to the problem at hand to be solved
mynum = Console.ReadLine(); //whatever is accepted thru d keyboard is stored in the var
mynum
} //notice anything while running the program? Error? Come 2 d next slide then!

Using System;
namespace shoprog
class myfirstprog
{
public static void main (string[] args)
int mynum;

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


18

Console.Write (“Indicate the value of the variable: ”);


//a conversion has to be done, else whatever is inputted is taking as string value(s)
mynum = Convert.ToInt32 (Console.ReadLine()); //note d dft types of ToInt; ToInt32 is d default
} //Run now! QED I suppose?

Using System;
namespace shoprog
class myfirstprog
{
public static void main (string[] args)
//furthering the program to capture two numbers, sum and output
int mynum1,mynum2, sum;
Console.Write (“Indicate the value of the 1st variable: ”);
mynum1 = Convert.ToInt32 (Console.ReadLine());
Console.Write (“Indicate the value of the 2nd variable: ”);
mynum2 = Convert.ToInt32 (Console.ReadLine());
sum = mynum1 + mynum2; //outputting sum, we can have:
Console.WriteLine (sum) //OR :
Console.WriteLine (“The sum of the two variables is: ” + sum); //OR try:
Console.WriteLine (“The sum of the two variables is: ”, sum);
Console.ReadKey(); }
Class Exercises
1. Write a C# program that captures the values of three (3) variables: m, n, q; computes
and output the sum of their squares.
2. Write a C# program that accepts the value of a variable, x, detects its even and prime
status. (taking u to control statement before hand)
3. Demonstrate the use of int.parse in Java as oppose to Convert.To…in C#. (as if am
taking u back to ur previous class – good for u anyway!)
4. Think of a programming problem that will yield a solution that uses the different
variants of Convert.To…aside Convert.ToInt variants.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


19

• THE STRUCTURE OF PYTHON


• Python, unlike C#, Java etc. that are compiled languages, it is an interpreted language.
• THE STRUCTURE OF PYTHON - STRUCTURE
• Program Header
• Declaration Section
• Program Body

• THE STRUCTURE OF PYTHON - HEADER


• Import sys
• Import os
• Import random
• Import pandas
• Import numpsy etc.

• THE STRUCTURE OF PYTHON - DECLARATION


• DATA TYPES (5 of them):
i. Numbers
ii. Strings
iii. Lists
iv. Tuples
v. Dictionary

• THE STRUCTURE OF PYTHON – BODY…


I/O Statements in Python
One of the commonest INPUT Statement in Python is INPUT, while that of OUTPUT
Statement is PRINT.
NB: Data/Values captured using INPUT are however assumed STRING unless a converter
(int) is used (similar to C#)

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


20

I/O Statements in Python – Programming Problem


Write a PYTHON program that accepts values for two integer variables num1 and num2,
carry out the computation of the product and summation and consequently output these
operations.

Solution (…from python shell or editor, code…)

We have seen the STRUCTURE of these two languages we are using as illustrations as regards
I/O Statement. Now, we come to CONTROL STRUCTURE and again, discuss for each language.
• Control Structure can be defined as statements that cause diversion in the normal
flow of program execution.
• They can be seen or described as program constructs that change or obstruct the
original intended pattern of program flow.
• According to the Control Structured Theorem, we have two types:
• Selection/Branching Control Statement
• Iterative/Repetitive Control Statement
For selection, generally we have:
i. If Statement
ii. If-Else Statement
iii. if-ElseIf Statement
iv. Switch – Case Statement

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


21

If Statement (Format – C#)


For Simple Statement,
If (condition) program statement
For Compound Statement,
if (condition){
program statement 1;
program statement 2;
.
.
program statement n;
}
• If Statement (Format – Python)
For Simple Statement,
If condition: program statement
OR
If condition:
program statement
• If Statement (Format – Python)
For Compound Statement,
if condition:
program statement 1
program statement 2
.
.
program statement n
}

Quick Exercise
• Using the 2 languages under consideration, write a program that computes for
pay_skolfee as my_salary – monthly_expenses iff the value of my_salary is greater
than monthly_expense.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


22

• If-Else Statement (Format – C & C#)


For Simple Statement,
If (condition) program statement1
else program statement2

• If-Else Statement (Format – C & C#)


For Compound Statement,
if (condition){
program statement 1a;
.
program statement n;
}
else {
program statement 1b;
.
program statement m;
}

• If-Else Statement (Format – Python)


For Simple Statement,
If condition : program statement1
else : program statement2
• If-Else Statement (Format – Python)
For Compound Statement,
If condition :
program statement1a
program statement2a
else :
program statement1b
program statement2b

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


23

Quick Exercise
• To be considered for admission in any Nigerian Universities, every student has to
write UTME & PUTME Exams aside the ‘O’ Level Exams. For most institutions, the
UTME is pegged at >=180, while the PUTME is set at >=40 and then shortlisting is to
an extent, possible. Code using the duo languages used in this course.

• If-ElseIf Statement (Format – C#)


For Simple Statement,
If (condition) program statement1
else if (condition) program statement2
else program statement3
• If-ElseIf Statement (Format – C#)
For Compound Statement,
If (condition) {
program statement1a;
.
program statement n; }

• If-ElseIf Statement (Format – C#)


For Compound Statement…
else if (condition) {
program statement2a;
.
program statement m; }
else
program statement 3a;
.
program statement q; }

• If-ElseIf Statement (Format – Python)

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


24

For Simple Statement,


If condition:
program statement1
else
if condition:
program statement2
else:
program statement3
• If-ElseIf Statement (Format – Python)
For Compound Statement,
If condition:
program statement1a
program statement1b
else
if condition:
program statement2a
program statement2b
else:
program statement3a
program statement3b
Quick Exercise
• Using C# and Python, write a program that captures value for your desired score in
csc413, classify the grade and output your matric, the score, and the grade (e.g. A,
B, C, D, E and F).
• SWITCH-CASE Statement (Format – C#)
Switch (Switch Variable){
Case (Case No/Value):
Program Statement;
.
Default: Program Statement / Literals;
}

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


25

• SWITCH-CASE Statement (Format – Python) - elif


if condition:
program statement # d least possible
elif condition:
program statement
elif condition:
program statement #continue with as many
else:
program statement #d default or last option

Quick Exercise
• Taking the trio languages under our ‘watch’, write an age classification program
such that:
i. <1 = ‘Expectant / New Arrival’
ii. >=1 but <6 = ‘Infants’
iii. >=6 but <18 = ‘Youths’
iv. >=18 but <40= ‘Adolescents’
v. >=40 but <100 = ‘Adults’
vi. >=100 = ‘Methuselahic Group’

Now to ITERATION, with emphasis on WHILE and FOR Statements.


• While Statement (Format – C#)
For Simple Statement,
while (condition)
program statement1;

• While Statement (Format – Python)


For Simple Statement,
while (condition) :
program statement1

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


26

• While Statement (Format – C#)


For Compound Statement,
while (condition) {
program statement 1;
program statement 2;
.
.
program statement n; }

• While Statement (Format – Python)


For Compound Statement,
while (condition) :
program statement 1
program statement 2
.
.
program statement n

Illustration
• A Python program to compute the sum of the first five (5) even integers.

Solution
evenno=2
sumeven=0
count=0
while count<=5:
sumeven = sumeven + evenno
evenno +=2
count +=1
print "The sum total of the even nos is: ", sumeven

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


27

The FOR Statement now…


• FOR Statement (Format – C & C#)
For Simple Statement,
for (init value, final value, incre/decre value) {
program statement1; }

• FOR Statement (Format – Python)


For Simple Statement,
for counter value in range (begin, end, step) :
program statement1

• FOR Statement (Format – C & C#)


For Compound Statement,
for (init value, final value, incre/decre value) {
program statement 1;
program statement 2;
.
.
program statement n; }

• FOR Statement (Format – Python)


For Compound Statement,
for counter value in range (begin, end, step) :
program statement 1
program statement 2
.
program statement n

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


28

Illustration
• A Python program output the first five (5) integers
Solution
for j in 1,2,3,4,5:
print j

NB: This is normal but not the idea way of representing the operation of the command
RANGE, ….but…ok, RUN first, then…
• A Python program output the first five (5) integers
…the more idea structure

Solution
for j in range(1,6): #not 1-5 but 1-6 - that is PYTHON for u
print j

NB: 0-5 indicates 0,1,2,3,4; 1-10 implies 1,2,3,4,5,6,7,8,9 (the formula is upper_value – 1.
Where it is indicated as …range(10) it means 0-9.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


29

CHAPTER FOUR
PROGRAMMING LANGUAGES: SYNTAX, SEMANTICS AND SCOPE

To use a programming language effectively we must study and understand it from three

perspectives:

 Syntax - the set of symbols and rules for forming terms.

 Semantics - the rules for transforming terms to terms.

 Pragmatics - using the particular constructs of the language.

Programming language is a notation that expresses certain algorithm to be executed by the

computer.

In the structure of any programming language, two elements are germane (in fact, these two

elements are what made up what we called the structure of programming language), these are:

 Syntax, and

 Semantics

 While Syntax refers to set of rules that guides the formation of codes that form programs,

Semantics implies the interpretation of those rules/codes that made up that programme. In

other words, it is one thing to code, it is another to rightly interpret what is coded.

 While the syntax may be correct (if not the program will not run), it is not impossible that

semantics error may go unnoticed – because the program will certainly run, only that

value/output gotten may be wrong because semantically something might have gone

wrong unnoticed in the way the code was interpreted, hence it affects the expected

output.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


30

Let’s discuss the two now…

SYNTAX

One possible definition of syntax would be “the rules that create valid programs.'' That definition

would cover a large part of what is usually considered semantics as well. In addition, syntax rules

with this definition would be undecidable, making it impossible for the compiler to verify syntax.

Usually when we think of syntax, we mean something that can be statically verified by the

compiler.

Another possible definition of syntax would be “the context-free grammar that generates

potentially valid programs.'' Usually, in traditional languages, each special form has its own rule

or rules within the grammar of the language. For instance, a while statement in C would have the

following grammar rule:

< while-statement> ::= while ( < expression> ) < statement> ;

which means that in order to write a while statement in C, you have to write the

word while followed by an opening parenthesis, followed by an expression, followed by a closing

parenthesis, followed by a statement followed by a semicolon.

The Syntax is regarded as the ‘lawyer’ of all programming languages.

The syntax is the custodian of programming rules that tells us the sentence that are legal to be

use and the ones that are illegal to be use in programming/coding; hence, it is called syntactic rules.

Syntactic rules deals with rules that approve/disapprove statement/sentences used in

programming/coding and not just the lettering.

The syntax diagram is used to represent programming statement.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


31

For instance,

Given the programming problem:

Z=x+y

Solution (using syntax diagram)

<identifier>  <expression> <operator> <expression>

identifier

expression operator expression

To simplify understanding and analyzing a language's syntax, we separate syntax into three levels:

lexical elements, context free syntax, and context sensitive syntax. In English, letters form

words which form sentences. In programming languages, characters form tokens, which form

terms. Tokens are lexical elements.

In programming languages our expectations of what certain symbols should mean, like "+" or "if"

may make us lose sight of the fact that both syntax and semantics really need to be defined to

define a language. However, there are places where this becomes pretty clear. For example, in a

C/C++ program the following is syntactically correct:

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


32

int x;

x = 2^3;

But what does it mean? i.e. what value does the variable x end up with? Not eight, in fact, but one!

You see, although we know it's syntactically correct, we don't know its semantics. Meaning must

be defined as well as form. (BTW: "^" is bitwise xor in C/C++.) It's not just a question of spelling

out what each keyword or operator symbol means, meaning of groups of symbols must also be

defined. For example, what about the following code fragment:

void foo(int x, int y, int z)

if (x < y < z)

In Java, this is actually syntactically incorrect. However, in C/C++ it is correct. But what does it

mean? What are the semantics here? Just knowing what < means isn't enough to tell you, actually.

You have to know <'s associativity, and you've got to know what type < returns ... and you even

have to know about C/C++ type automatic type promotion rules are, and what true and false really

are. And even then, it certainly doesn't mean what a newbie would expect. Syntax tells you whether

or not x < y < z is valid in the language - and this depends on the language, as we've seen - but you

need the semantics to know what the expression actually means.

Exercise

 Write a C program that declares an array x, initializes it, and increments each element.

 Write a C program that does it using recursion.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


33

SEMANTICS

In programming language theory, semantics is the field concerned with the rigorous

mathematical study of the meaning of programming languages. It does so by evaluating the

meaning of syntactically valid strings defined by a specific programming language, showing the

computation involved.

Semantics of a language provide meaning to its constructs, like tokens and syntax structure.

Semantics help interpret symbols, their types, and their relations with each other. Semantic

analysis judges whether the syntax structure constructed in the source program derives any

meaning or not.

Again, semantics simply implies meaning/interpretation associated with a syntax/syntactic rule.

To discuss semantic, the following concepts will be explained: Binding, Scope, and Lifetime of a

variable.

Binding

In a typical programming environment, every program/code consists of program entities (e.g.

variables, subprogram, statements (e.g. I/O statements, Array statements etc.) and attributes (e.g.

data type etc.).

Program entities in turn consist of attributes (e.g. name, type, storage area etc.).

Ideally, attributes must be specified before an entity can be processed.

Binding is the programming act of specifying the exact nature of an attribute. In other words,

Binding is the mapping of attributes to an entity.

Succinctly put, Binding is associating/assigning properties to entities etc.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


34

Majorly, Binding can occur at two stages: @design/definition/coding time, and

@compile/execution/run time.

This is largely language-dependent that is, whether Binding can occur at coding time or run time

is largely dependent on the type of programming language in use.

For instance, Binding is mostly done at coding time in FORTRAN. For instance, to bind data type

(attribute) to a variable (entity) in FORTRAN, this can only be done at

design/definition/development/coding time and not during execution/compile/run time.

Let’s examine/experiment this by opening and coding in FORTRAN:

Program ajsample1

implicit none

integer::waste,keep, preserve

write(*,*)'Enter waste value: '

read(*,*)waste

write (*,*)'Enter keep value: '

read(*,*)keep

preserve = keep-waste

write(*,*)'The value preserved is:'

write(*,*)preserve

end program ajsample1

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


35

(Directly, this program will run, but lease note how this will be demonstrated/recoded now…as an

attempt is made to bind/declare preserve dynamically during run time – FORTRAN will not allow

this to be done at compile/run time, by its design, this can only be done at coding/design time).

Program ajsample1

implicit none

integer::waste,keep

write(*,*)'Enter waste value: '

read(*,*)waste

write (*,*)'Enter keep value: '

read(*,*)keep

integer::preserve

preserve = keep-waste

write(*,*)'The value preserved is:'

write(*,*)preserve

end program ajsample1

(Note the error statement in FORTRAN and tell me when we meet!)

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


36

see another example in C++:

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop
*/

int main(int argc, char** argv) {

int a, b;

cout<<"Enter 1st value:"; cin>>a;

cout<<"Enter 2nd value:"; cin>>b;

for (int i = 0; i<3;i++){

int findme = a+b;

cout<<"The value found is:"<<findme;

float findme = a/b;

cout<<"The value found is:"<<findme;

return 0;

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


37

Now, aside Binding been language-dependent, it is also dependent on the type/nature of the
commands/statements/entities to be defined/programmed/bounded.

For instance, you can only specified/defined an array in QBasic at the beginning/definition point
of the program (@definition/development/coding time) e.g. DIM. This is the same in most object-
oriented programming languages like C++, C# etc. as demonstrated in the C++ codes below:

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop
*/

int main(int argc, char** argv) {

int matno[10];

int csc811_score[10];

int csc822_score[10];

int result[10];

//capturing data...

for(int i=0;i<10;i++)

cout<<"Enter Matric for Student "<<i+1<<":"; cin>>matno[i];

cout<<"Enter csc811 for Student "<<i+1<<":"; cin>>csc811_score[i];

cout<<"Enter csc822 for Student "<<i+1<<":"; cin>>csc822_score[i];

return 0;

These examples are what we called static binding. However, most object-oriented programming
languages have facilities for implementing dynamic binding.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


38

For instance, modifying the C++ program above, we have:

#include <iostream>

using namespace std;

/* run this program using the console pauser or add your own getch, system("pause") or input loop
*/

int main(int argc, char** argv) {

int matno[n];

int csc311_score[n];

int csc305_score[n];

int result[n];

//capturing to specify the array size...

cout<<"Input your array size: "; cin>>n;

//capturing data...

for(int i=0;i<n;i++)

cout<<"Enter Matric for Student "<<i+1<<":"; cin>>matno[i];

cout<<"Enter csc311 for Student "<<i+1<<":"; cin>>csc311_score[i];

cout<<"Enter csc305 for Student "<<i+1<<":"; cin>>csc305_score[i];

return 0;

Assignment 1 (under this section)

Discuss the concept of SCOPE with appropriate programming illustration.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


39

There are three main styles of describing semantics: operational, denotational, and

axiomatic.

 Operational semantics

 Denotational semantics

 Axiomatic semantics

Operational Semantics

An operational semantics is a mathematical model of programming language execution. It is, in

essence, an interpreter defined mathematically. However, an operational semantics is more precise

than an interpreter because it is defined mathematically, and not based on the meaning of the

language in which the interpreter is written. Formally, we can define operational semantics as

follows.

An operational semantics for a programming language is a mathematical definition of its

computation relation, e ==> v, where e is a program in the language.

e ==> v is mathematically a 2-place relation between expressions of the language, e, and values of

the language, v. Integers and booleans are values. Functions are also values because they don’t

compute to anything. e and v are metavariables, meaning they denote an arbitrary expression or

value, and should not be confused with the (regular) variables that are part of programs.

An operational semantics for a programming language is a means for understanding in precise

detail the meaning of an expression in the language. It is the formal specification of the language

that is used when writing compiles and interpreters, and it allows us to rigorously verify things

about the language.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


40

Denotational Semantics

In denotational semantics, the basic idea is mapping every syntactic entity associated with a

programming language into some form of mathematical entity, translating programming

language constructs into mathematical objects.

Denotational semantic definition has five parts:

 Semantic equations

 Syntactic categories

 Semantic functions

 Backus normal form (BNF) defining the structure of the syntactic categories

 Value domains

Denotational semantics have been developed for modern languages which have features like

exceptions and concurrency. One of the important features of denotational semantics is that

semantics should be compositional, meaning denotation of a programming phrase can be

constructed from the denotations of its sub-phrases.

There are some distinct advantages associated with denotational semantics. It is the easiest

mechanism for describing the meaning of smaller programs compared to other alternatives.

Denotational semantics is capable of explaining state in programs. However, denotational

semantics tend to be very complex for describing advanced features like goto statements and

recursions.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


41

Axiomatic Semantics
Axiomatic semantics are semantic expressions of the relationships inherent in a piece of code.

These expressions can be helpful in describing how some piece of software works. An interesting

thing about axiomatic semantics as contrasted to other types of expressions is that they are fairly

agnostic of specific results and conditions. Rather, axiomatic semantics describe the way that a

system works. One way to think of this is using the root word, axiom, which implies some broader

truism about a system. For example, an axiomatic semantical statement about a certain function

would describe what it is meant to do, what sort of argument it takes, and what sort of result it

returns. This would not require knowledge of the actual variables involved.

In summary,

The syntax of a programming language is the set of rules governing the formation of

expressions in the language. The semantics of a programming language is

the meaning of those expressions.

SCOPE

Scope is the area of the program where an item (be it variable, constant, function, etc.) that has

an identifier name is recognized. In our discussion, we will use a variable and the place within

a program where the variable is defined determines its scope.

An important idea in programming is scope. Scope defines where variables can be accessed or

referenced. A scope in any programming is a region of the program where a defined variable

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


42

can have its existence and beyond that variable it cannot be accessed. There are three places where

variables can be declared in C programming language − Inside a function or a block which is

called local variables.

Scope refers to the visibility of variables. In other words, which parts of your program can see or

use it. Normally, every variable has a global scope.

The scope of an identifier name binding – an association of a name to an entity, such as a variable

– is the region of a computer program where the binding is valid: where the name can be used to

refer to the entity. Such a region is referred to as a scope block. In other parts of the program, the

name may refer to a different entity (it may have a different binding), or to nothing at all (it may

be unbound).[1]

Discussion

Scope is the area of the program where an item (be it variable, constant, function, etc.) that has an

identifier name is recognized. In our discussion, we will use a variable and the place within a

program where the variable is defined determines its scope.

Global scope (and by extension global data storage) occurs when a variable is defined “outside of

a function”. When compiling the program it creates the storage area for the variable within the

program’s data area as part of the object code. The object code has a machine code piece, a data

area, and linker resolution instructions. Because the variable has global scope it is available to all

of the functions within your source code. It can even be made available to functions in other object

modules that will be linked to your code; however, we will forgo that explanation now. A key

wording change should be learned at this point. Although the variable has global scope, technically

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


43

it is available only from the point of definition to the end of the program source code. That is

why most variables with global scope are placed near the top of the source code before any

functions. This way they are available to all of the functions.

Local scope (and by extension local data storage) occurs when a variable is defined “inside of a

function”. When compiling, the compiler creates machine instructions that will direct the creation

of storage locations on an area known as the stack which is part of the computer’s memory.

These memory locations exist until the function completes its task and returns to its calling

function. In assembly language, we talk about items being pushed onto the stack and popped off

the stack when the function terminates. Thus, the stack is a reusable area of memory being used

by all functions and released as functions terminate. Although the variable has local scope,

technically it is available only from the point of definition to the end of the function.

The parameter passing of data items into a function establishes them as local variables.

Additionally, any other variables or constants needed by the function usually occur near the top of

the function definition so that they are available during the entire execution of the function’s code.

Scope is an important concept for modularization. Program control functions may use global scope

for variables and constants placing them near the top of the program before any functions. Specific

task functions use only local scope variables by passing data as needed into the function with

parameter passing and creating local variables and constants as needed. Any information that needs

to be communicated back to the calling function is again done via parameter passing. This closed

communications model that passes all data into and out of a function creates an important

predecessor concept for encapsulation which is used in object-oriented programming.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


44

Key Terms

data area

A part of an object code file used for storage of data.

global scope

Data storage defined outside of a function.

local scope

Data storage defined inside of a function.

scope

The area of a source code file where an identifier name is recognized.

stack

A part of the computer’s memory used for storage of data.

DATA TYPES

A data type is a classification of data which tells the compiler or interpreter how the programmer

intends to use the data. Most programming languages support various types of data, including

integer, real, character or string, and Boolean.

Data types are divided into two groups:

 Primitive data types - includes byte , short , int , long , float , double , boolean and char.

 Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in

a later chapter)
ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.
45

A data type is a means of classifying the type of data that a variable or object can hold in computer

programming. Data types are an important factor in all computer programming languages,

including C#, C++, JavaScript, and Visual Basic. When programmers develop computer

software—whether that’s desktop or web-based—data types must be assigned and applied

correctly in order to guarantee proper outcomes and an error-free program.

In programming, a data type is a categorization that specifies what kind of operation can be applied

to it without resulting in an error.

The data type determines which operations can be safely executed to develop, transpose, and apply

the variable to another computation. When a programming language needs a variable to be used

only in ways that follow its data type, that language is said to be strongly typed. Doing this reduces

errors, because while it is reasonable to ask the computer to multiply a float by an integer (3.4 x

3), it is unreasonable to ask the computer to multiply a float by a string (3.4 x Sam). When a

programming language allows a variable to assume a different data type, the language is said to

be weakly typed.

Strongly typed and weakly typed programming languages are commonly-held

misconceptions. There is a concept of type safety, whereby a programming language constrains

or restricts type error.

Common Data Types

 Integer – a whole number that can have a positive, negative, or zero value. It cannot be a

fraction, nor can it include decimal places. It is commonly used in programming, especially

for increasing values. Addition, subtraction, and multiplication of two integers results in

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


46

an integer. However, division of two integers may result in either an integer or a

decimal. The resulting decimal can be rounded off or truncated in order to produce an

integer.

 Character – any number, letter, space, or symbol that can be entered in a computer. Every

character occupies one byte of space.

 String – used to represent text. It is composed of a set of characters that can include spaces

and numbers. Strings are enclosed in quotation marks to identify the data as strings, and

not as variable names, nor as numbers.

 Floating Point Number – a number that contains decimals. Numbers that contain fractions

are also considered floating-point numbers.

 Array – a kind of a list that contains a group of elements which can be of the same data

type as an integer or string. It is used to organise data for easier sorting and searching of

related sets of values.

 Varchar – as the name implies, a varchar is a variable character, on account of the fact

that the memory storage has variable length. Each character occupies one byte of space,

plus 2 bytes additional for length information.

Note: Use Character for data entries with fixed lengths, like phone numbers, but use Varchar for

data entries with variable lengths, like address.

Boolean – used for creating true or false statements. To compare values the following operators

are being used: AND, OR, XOR, and NOT.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


47

Discussion

Our interactions (inputs and outputs) with a program are treated in many languages as a stream of

bytes. These bytes represent data that can be interpreted as representing values that we understand.

Additionally, within a program, we process this data in various ways such as adding them up or

sorting them. This data comes in different forms. Examples include:

 your name – a string of characters

 your age – usually an integer

 the amount of money in your pocket – usually a value measured in dollars and cents (something

with a fractional part)

A major part of understanding how to design and code programs is centered in understanding the

types of data that we want to manipulate and how to manipulate that data.

Common data types include:

Data Type Represents Examples

integer whole numbers -5, 0, 123

floating point (real) fractional numbers -87.5, 0.0, 3.14159

String A sequence of characters "Hello world!"

Boolean logical true or false true, false

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


48

nothing no data null

A data type defines a set of values and a set of operations that can be applied on those values.

The common data types usually exist in most programming languages and act or behave similarly

from language to language. Additional complex and/or composite data types may exist and vary

from language to language.

boolean

A data type representing logical true or false.

floating point

A data type representing numbers with fractional parts.

integer

A data type representing whole numbers.

string

A data type representing a sequence of characters.

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


49

 Boolean

Boolean
Result Condition
Operator

x AND y True If both x and y are True

x AND y False If either x or y is False

x OR y True If either x or y, or both x and y are True

x OR y False If both x and y are False

x XOR y True If only x or y is True

x XOR y False If x and y are both True or both False

NOT x True If x is False

NOT x False If x is True

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.


50

 Date, Time and Timestamp – these data types are used to work with data containing dates

and times.

Date Type Value

DATE Year, Month and Day

TIME Hour, Minute and Second

TIMESTAMP Year, Month, Day, Hour, Minute, Second and Microsecond

Exercises

1. Differentiate between the types of Semantics

2. Distinguish between Syntax and Semantics

3. Describe Data Types

ORGANISATION OF PROGRAMMING LANGUAGES DR. AJAYI, O. O.

You might also like