0% found this document useful (0 votes)
65 views48 pages

CS508 Final Term Lecture 19 To 45

CS508 Modern Programming Languages Short Notes for Final Term Lecture 19 to 23

Uploaded by

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

CS508 Final Term Lecture 19 To 45

CS508 Modern Programming Languages Short Notes for Final Term Lecture 19 to 23

Uploaded by

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

CS508 Final Term Preparation | Lecture 19 to 45

Lecture 19 to 21:
Functional Programming Paradigm and LISP: Functional programming is a style of programming that
emphasizes the evaluation of expressions, rather than execution of commands. The expressions in these
languages are formed by using functions to combine basic values. A functional language is a language
that supports and encourages programming in a functional style.
LISP is a representative language of this style of programming.
Lisp stands for “LISt Process”. It was invented by John McCarthy in 1958 at MIT. It has simple data
structure (atoms and lists) and makes heavy use of recursion. It is an interpretive language and has
many variations. The two most popular versions are Scheme and Common Lisp (de facto industrial
standard). It is the most widely used AI programming language.
Valid Objects: A LISP program has two types of elements: atoms and lists.
Atoms: Atoms include numbers, symbols, and strings. It supports both real numbers and integers.
Symbols: a symbol in LISP is a consecutive sequence of characters (no space). For example a, x, and
price-of-beef are symbols. There are two special symbols: T and NIL for logical true and false.
Strings: a string is a sequence of characters bounded by double quotes. For example "this is red" is a
string.
S-expression: An S-expression (S stands for symbolic) is a convention for representing data or an
expression in a LISP program in a text form. It is characterized by the extensive use of prefix notation
with explicit use of brackets (affectionately known as Cambridge Polish notation).
S-expressions are used for both code and data in Lisp. S-expressions were originally intended only as
machine representations of human-readable representation of symbols, but Lisp programmers soon
started using S-expressions as the default notation.
S-expressions can either be single objects or atoms such as numbers, or lists.
Lists: List is the most important concept in LISP. A list is a group of atoms and/or lists, bounded by ( and
). For example (a b c) and (a (b c)) are two lists. In these examples the list (a b c) is a list of atoms a, b,
and c, whereas (a (b c)) is a list of two elements, the first one an atom a, and the second one a list (b c).
Top elements of a list: The first-level elements in LISP are called top-level elements. For example top
elements of list (a b c) are a, b, and c. Similarly, top elements of list (a (b c)) are a and (b c).
An empty list is represented by nil. It is the same as ().
Function calls: In LISP, a function and a function call is also a list. It uses prefix notation as shown below:
(function-name arg1 ... argn)
A function call returns function value for the given list of arguments. Functions are either provided by
LISP function library or defined by the user.
Following are some examples of function calls. Note that the first symbol is the name of the function
and the rest are its arguments.
>(+ 1 3 5)
9
Note that the arithmetic functions may take more than two arguments.
>(/ 3 5)
3/5
When we use two integers in division, the answer is converted into fraction.
>(/ 3.0 5)
0.59999999999999998
Note the difference between integer and real division.

1
CS508 Final Term Preparation | Lecture 19 to 45

>(sqrt 4)
2
Evaluation of S-expression: S-expressions are evaluated as follows:
1) Evaluate an atom.
• numerical and string atoms evaluate to themselves;
• symbols evaluate to their values if they are assigned values, return Error,otherwise;
• the values of T and NIL are themselves.
2) Evaluate a list
• evaluate every top element of the list as follows, unless explicitly forbidden:
• the first element is always a function name; evaluating it means to call the function body;
• each of the rest elements will then be evaluated, and their values returned as the arguments
for the function.
Examples:
1.
>(+ (/ 3 5) 4)
23/5
The first element is + so we make a call to + function with (/ 3 5) and 4 as arguments.
Now (/ 3 5) is evaluated and the answer is 3/5. After that 4 is evaluated to itself and thus returns 4. So,
3/5 and 4 are added to return 23/5.
2.
>(+ (sqrt 4) 4.0)
6.0
This example is similar to the first example.
3.
>(sqrt x)
Error: The variable
X is unbound.
This code generates an error as the symbol x is not associated with any value and thus cannot be
evaluated.
setq, set, and setf are used to assign a value to a symbol.
For example, the following code assigns a value 3 to symbol x.
>(setq x 3.0)
3.0
Setq: is a special form of function (with two arguments). The first argument is a symbol which will not
be evaluated and the second argument is a S-expression, which will be evaluated. The value of the
second argument is assigned to be the value of the first argument.
To forbid evaluation of a symbol a quote or ’ is used.
For example
>(quote x)
x
Similarly if we have
>(setq x 3.0)
3.0
and then we do

2
CS508 Final Term Preparation | Lecture 19 to 45

>(setq y x)
3.0
then y will also have a value 3.0
But if we use a quote as shown below
<(setq y ‘x)
x
then x will not be evaluated and y will get the value x instead of 3.0.
Functions: There are many built-in function is LISP. This includes math functions as well as
functions for manipulating lists. The math functions include:
– +, -, *, /, exp, expt, log, sqrt, sin, cos, tan, max, min
with the usual meanings.
List Constructors: Lists can be constructed (created and extended) with the help of three basic
functions. These are cons, list and append.
cons takes two arguments. The first argument is a symbol and the second one is a list. It inserts the first
argument in front of the list provided by the second argument. It is shown in the following example:
>(cons 'x L) ; insert symbol x at the front of list L, which is
(X A B C) ; (A B C)
list takes arbitrary number of arguments and makes a list of these arguments as shown below:
>(list 'a 'b 'c) ; making a list with the arguments as its elements
(A B C) ; if a, b, c have values A, B, C, then (list a b c) returns list (A B C)
append takes two lists as arguments and appends one list in front of the other as shown below:
>(append '(a b) '(c d))
(A B C D) ; appends one list in front of another
List Selectors: In order to select elements from a list, selectors functions are used. There are two basic
selector functions known as first (or car) and rest (or cdr). The rest can be build with the help of these
functions.
first (or car) takes a list as an argument and returns the first element of that list as shown in the
following examples:
>(first '(a s d f))
a
>(first '((a s) d f))
(a s)
>(setq L '(A B C))
(A B C)
>(car L)
A
rest (or cdr) takes a list as its argument and returns a new list after removing the first element from the
list. This is demonstrated in the following examples:
>(rest '(a s d f))
(s d f).
>(rest '((a s) d f))
(d f)
>(rest '((a s) (d f))
((d f))

3
CS508 Final Term Preparation | Lecture 19 to 45

>(setq L '(A B C))


(A B C)
>(cdr L)
(B C)
Some of the other useful list manipulation functions are:
>(reverse L) ; reverses a list
(C B A)
and
>(length L) ; returns the length of list L
3
Predicates: A predicate is a special function which returns NIL if the predicate is false, T or anything
other than NIL, otherwise. Predicates are used to build Boolean expressions in the logical statements.
The following comparative operators are used as functions for numerical values and return a T or NIL.
=, >, <, >=, <=;
For example:
¾ (= (+ 2 4) (* 2 3))
¾T
¾ (> (- 5 2) (+ 3 1))
¾ NIL
For non numeric values you can only check for equality using equal or eq.
Some other useful predicates are listed below:
atom: test if x is an atom
listp: test if x is a list
Also number, symbolp, null can be used to test whether the operand is a number, symbol, or a null
value.
Set Operations: A list can be viewed as a set whose members are the top elements of the list. The list
membership function is a basic function used to check whether an element is a member of a list or not.
It is demonstrated with the help of the following code:
>(setq L '(A B C))
>(member 'b L) ; test if symbol b is a member (a top element) of L
(B C) ; if yes, returns the sublist of L starting at the
; first occurrence of symbol b
>(member ‘b (cons 'b L))
(B A B C)
Note here that the mathematical definition of a set is different from the LISP definition. In
Mathematics, a symbol cannot be repeated in a set whereas in LIST there is no such restriction.
If an element is not present in the list, it returns NIL as shown below.
>(member x L)
NIL ; if no, returns NIL
Some of the other set operations are defined as below:
>(union L1 L2) ; returns the union of the two lists
>(intersection L1 L2) ; returns the intersection of the two lists
>(set-difference L1 L2) ; returns the difference of the two lists

4
CS508 Final Term Preparation | Lecture 19 to 45

Defining LISP functions: In LISP, defun is used to write a user-defined function. Note that different
dialects ofLISP may use different keywords for defining a function. The syntax of defun is as below:
(defun func-name (arg-1 ... Arg-n) func-body)
This concept is demonstrated with the help of the following example:
>(defun y-plus (x) (+ x y)) ;definition of y-plus
Conditional control: if, when and cond: LISP has multiple conditional control statements. The set
includes if, when, and cond. In the following pages we study these statements one by one.
if statement: The if statement has the following syntax:
(if <test> <then> <else>)
That is, an if statement has three parts: the test, the then part, and the else part. It works almost exactly
like the if statement in C++.
cond statement: The cond statement in LISP is like the switch statement in C++. There is however a
slight different as in this case each clause in the cond requires a complete Boolean test. That is, just like
multiple else parts in the if statement where each needs a separate condition.
Syntax of cond is as shown below:
>(cond (<test-1> <action-1>)
(<test-2> <action-2>)
...
(<test-k> <action-k>))
Each (<test-i> <action-i>) is called a clause.
Recursion: Recursion is the main tool used for iteration.
Iteration: dotimes and dolist: A part from recursion, in LISP we can write code involving loops using
iterative non- recursive mechanism. There are two basic statements for that purpose: dotimes and
dolist. These are discussed in the following paragraphs.
Dotimes: dotimes is like a counter-control for loop. Its syntax is given as below:
(dotimes (count n result) body)
It executes the body of the loop n times where count starts with 0, ends with n-1.
The result is optional and is to be used to hold the computing result. If result is given, the function will
return the value of result. Otherwise it returns NIL. The value of the count can be used in the loop body.
Dolist: The second looping structure is dolist. It is used to iterate over the list elements, one at a time. Its
syntax is given below:
(dolist (x L result) body)
Property Lists: Property lists are used to assign/access properties (attribute-value pairs) of a symbol.
The following functions are used to manipulate a property list.
To assign a property: (setf (get object attribute) value)
To obtain a property: (get object attribute)
To see all the properties; (symbol-plist object)
 We can remove a property by using the remprop function as shown below:
> (remprop ‘a ‘WEIGHT)
T
Arrays: Although the primary data structure in LISP is a list, it also has arrays. These are data type to
store expressions in places identified by integer indexes. We create arrays by using the linear-array
function as shown below:

5
CS508 Final Term Preparation | Lecture 19 to 45

(setf linear-array (make-array ‘(4)))


This statement creates a single dimension array of size 4 by the name of linear-array with indices from 0
to 3.
Here is an example of a two-dimensional array:
(setf chess-board (make-array ‘(8 8)))
Once created, we can store data at the desired index as follows:
(setf (aref chess-board 0 1) ‘WHITE-KNIGHT)
(setf (aref chess-board 7 4) ‘BLACK-KING)
Here, aref is the array reference.
What made Lisp Different?: LISP was one of the earliest programming language. It was designed at
MIT for artificial intelligence and it has since been the defacto standard language for the AI community,
especially in the US.
LISP program composed of expression. They are in fact trees of expression, each of which returns a
value. It has Symbol types: symbols are effectively pointer to strings stored in a hash table. One very
important aspect of LISP is that the whole language is there. That is, there is no real distinction between
read-time, compile-time and runtime.
This provides a very powerful feature allowing the programmer to write programs that write programs.
From a programming language design point of view, LISP was the first to introduce the following
concepts:
• Conditionals: such as if-then-else construct.
• Function types: where functions are just like integers and strings
• Recursion: first language to support it.
• Dynamic typing: all variable are pointers.
• Garbage-Collection.
• Programs composed of expressions.
• A symbol type.
• The whole program is a mathematical function

Lecture 22 to 26:
PROLOG stands for PROgramming in LOGic and was design in 1975 by Phillippe Roussell. It is a
declarative programming language and is based upon Predicate Calculus. A program in PROLOG is
written by defining predicates and rules and it has a built-in inference mechanism. Unfortunately, there
is no effective standardization available.
PROLOG Paradigm
As mentioned earlier, PROLOG draws inferences from facts and rules. It is a declarative language in
which a programmer only specifies facts and logical relationships. It is non- procedural. That is we only
state "what" is to be done and do not specify "how" to do it.
One of the main features of this language is its ability to handle and process symbols. Hence it is used
heavily in AI related applications. It is an interactive (hybrid compiled/interpreted) language and its
applications include expert systems, artificial intelligence, natural language understanding, logical
puzzles and games.
PROLOG Programming: PROLOG programming follows the following steps:
• Declaring some facts about objects and their relationships
• Defining some rules about objects and their relationships

6
CS508 Final Term Preparation | Lecture 19 to 45

• Asking questions about objects and their relationships


The PROLOG Programmer loads facts and rules into the database and makes queries to the database to
see if a fact is in the database or can be implied from the facts and rules therein.
This is depicted in the following diagram.

Facts:
• Facts are used to represent unchanging information about objects and their relationships.
• Only facts in the PROLOG database can be used for problem solving.
• A programmer inserts facts into the database by typing the facts into a file and loading (consulting) the
file into a running PROLOG system.
Queries: Queries are used to retrieve information from the database. A query is a pattern that
PROLOG is asked to match against the database and has the syntax of a compound query.
Logic Programming: Logic programming is a form of declarative programming. In this form, a program is
a collection of axioms where each axiom is a Horn clause of the form:
H :- B1, B2, ..., Bn.
Where H is the head term and Bi are the body terms, meaning H is true if all Bi are true.
The basic proof technique is Modus Ponens i.e.
A -> B (If A is true then B is also true but it does not mean that if B is true then A is also true).
Resolution: To deduce a goal (theorem), the logic programming system searches axioms and combines
sub-goals. For this purpose we may apply forward (from fact to goal) or backward (from goal to fact)
chaining. For example, given the axioms:
C :- A, B.
D :- C.
Given that A and B are true, forward chaining (from fact to goal) deduces that C is true because C :- A, B
and then D is true because D :- C.
Backward chaining (from goal to fact) finds that D can be proven if sub-goal C is true because D :- C. The
system then deduces that the sub-goal is C is true because C :- A, B. Since the system could prove C it
has proven D.
Prolog Uses backward chaining because it is more efficient than forward chaining for larger collections
of axioms.

7
CS508 Final Term Preparation | Lecture 19 to 45

PROLOG syntax:
Constants: There are two types of constants in Prolog: atoms and numbers.
Atoms:
• Alphanumeric atoms - alphabetic character sequence starting with a lower case letter.
Examples: apple a1 apple_cart
• Quoted atoms - sequence of characters surrounded by single quotes. Examples: ‘Apple’ ‘hello
world’
• Symbolic atoms - sequence of symbolic characters. Examples: & < > * - + >>
• Special atoms. Examples: ! ; [ ] {}
Numbers:
Numbers include integers and floating point numbers.
Examples: 0 1 9821 -10 1.3 -1.3E102.
Variable Names
In Prolog, a variable is a sequence of alphanumeric characters beginning with an upper case letter or an
underscore. Examples: Anything _var X _
Compound Terms (structures):
A compound term is an atom followed by an argument list containing terms. The arguments are
enclosed within brackets and separated by commas.
Example: isa(dog, mammal)
Comments:
In Prolog % is used to write a comment just like // in C++. That is after % everything till the end of the
line is a comment.
Important points to note
• The names of all relationships and objects must begin with a lower case letter.
o For example studies, ali, programming
• The relationship is written first and the objects are enclosed within parentheses and are
written separated by commas.
o For example studies(ali, programming)
• The full stop character ‘.’ must come at the end of a fact.
• Order is arbitrary but it should be consistent.
Logic Representation: Propositional Calculus: Propositional Logic is a set of Boolean statements. It
involves logic connectives such as “¬ ∧ ∨ ⇔ ⇒.”

8
CS508 Final Term Preparation | Lecture 19 to 45

Example – a family:If we had the following atomic statements:


p: Ahmed is father of Belal
q: Ahmed is brother of Aslam
r : Aslam is uncle of Belal
Then the following table shows the meanings in English for some logical statements in propositional
calculus:

Sections of Prolog Program:


Predicates
Predicates are declarations of relations or rules. They are just like function prototypes (declaration). A
predicate may have zero or more arguments. Example of predicates is: man(symbol)
family()
a_new_predicate (integer, char)
Clauses: Clauses are definition(s) of Predicate sentence or phrase. It has two types: rules and facts.
A rule is a function definition. It may have 0 or more conditions. A fact has all parameters as constants
and it cannot contain any condition.
Example – Fact:
brother(ahmed, chand).
Saying that ahmed and chand are brothers.
Example – Rule:
brother(X,Y):-
man(X),
man(Y),
father(Z,Y),
father(Z,X).
It says that two symbols, X and Y, are brothers if X is a man and Y is a man and their father is same.
Goal:
• Goal is the objective of the program.
• There can be only and exactly one instance of the goal in a program.
• It is the only tentative section of the program.
• It may be thought as the main() function of prolog.
• The truth value of the goal is the output of the program.
• Syntactically and semantically, it is just another clause.
• It may be empty, simple (one goal), or compound (sub-goals).
Prolog Variables: Prolog variable are actually constant placeholders and NOT really variables. That is, a
value to a variable can be bound only once and then it cannot be changed. These variables are loosely
typed. A variable name starts with capital letter or underscore. Here are some examples of variable
names:
brother(ahmed, Ahmed) % ahmed is a constant whereas Ahmed is a variable

9
CS508 Final Term Preparation | Lecture 19 to 45

brother(ahmed, _x) % _x is a variable


Brother(ahmed, X) % X is a variable
Anonymous variable:
The _ is a special variable. It is called the anonymous variable. It is used as a place holder for a value that
is not required. For example _ is used as a variable in the following clause: brother(ahmed, _)
PROLOG Lists: In Prolog, a list is a sequence of terms of the form
[t1, t2, t3, t4, ..., tn]
where term ti is the ith element of the list
Examples:
1. [a,b,c] is a list of three elements a, b and c.
2. [[a,list,of,lists], and, numbers,[1,2,3]] is a four element list, the first and last are themselves lists.
3. [ ] is the ‘empty list’. It is an atom not a list data type. This is a fixed symbol. And it will always have
the same meaning that’s why it is treated as atom not list.
Working with Lists:
1. Lists are used to build compound data types.
2. A list can have elements of arbitrary type and size.
3. There is no size limits.
4. Representation in prolog is very concise (short).
5. head – tail separator
a. The vertical bar ‘|’ is used to separate the head and tail of a list as shown below:
[<head>|<tail>]
b. In this case, head is an element whereas tail is list of the same sort.
c. The | has dual purpose in Prolog; it is used for list construction as well as list dismantling.
Here as some examples of lists:
[a, bc, def, gh, i] % a simple list of five elements
[] % an empty list
[1,2,3] % a simple list of three elements
[1, 2 | [3] ] % same as above; a list of three elements with 1 and 2 as head and
% [3] as tail. When you join head and tail you get [1 2 3].
[1 | [2, 3] ] % another way of writing the same thing again. This time the head
% is only 1 and the tail is [2 3]. Concatenation of these two gives
% [1 2 3].
[1, 2, 3 | [ ] ] % same thing again but with a different head and tail formation
 Recursion is the basic tool for writing programs in Prolog.
Sorting: in order to sort a list, we only specify what is meant by sorting and not how to do it.
sorted ([ ]). % an empty list or list with only one element
sorted ([X]). % is already sorted
sorted ([X, Y | list]) :- % recursive step
X <= Y, % a list is sorted if every element in the list
sorted ([Y | list]). % is smaller than the next element in the list.
List Membership:
member(X, [X|T]). % X is a member of the list if it is the first
% element
member(X, [H|T]) :- member(X, T).

10
CS508 Final Term Preparation | Lecture 19 to 45

% otherwise recursively check it in the rest of


% the list
Subset:
subset( [ ], Y ). % The empty set is a subset of every set.
subset( [ A | X ], Y ) :- % recursive step
member( A, Y ), subset( X, Y ).
intersection
% Assumes lists contain no duplicate elements.
intersection( [ ], X, [ ] ).
intersection( [ X | R ], Y, [ X | Z ] ) :-
member( X, Y ), !, intersection( R, Y, Z ).
intersection( [ X | R ], Y, Z ) :- intersection( R, Y, Z ).
union
union( [ ], X, X ).
union( [ X | R ], Y, Z ) :- member( X, Y ), !, union( R, Y, Z ).
union( [ X | R ], Y, [ X | Z ] ) :- union( R, Y, Z ).

Lecture 27 to 30:
Java was developed at Sun in the early 1990s and is based on C++. It looks very similar to C++ but it is
significantly simplified as compared to C++. That is why Professor Feldman says that Java is C++--. It
supports only OOP and has eliminated multiple inheritance, pointers, structs, enum types, operator
overloading, goto statement from C++. It includes support for applets and a form of concurrency.
The First Program
Here is the famous Hello World program in Java.
class HelloWorld {
public static void main( String [ ] args )
{
System.out.println("Hello world!");
}
}
It may be noted that as Java supports only OOP, in Java, every variable, constant, and function (including
main) must be inside some class. Therefore, there are no global variables or functions in Java. In
addition, the following may be noted:
• Function main is member of the class.
• Every class may have a main function; there may be more than one main function in a Java
program.
• The main must be public static void.
• The main may have one argument: an array of String. This array contains the command-line
arguments.
• There is no final semi-colon at the end of the class definition.
Java Files: In Java the source code is written in the .java file. The following restrictions apply:
(1) Each source file can contain at most one public class.
(2) If there is a public class, then the class name and file name must match.

11
CS508 Final Term Preparation | Lecture 19 to 45

Furthermore, every function must be part of a class and every class is part of a package. A public class
can be used in any package and a non-public class can only be used in its own package.
The Java Bytecode is created by the Java compiler and is stored in .class file. This file contains ready to
be exected Java bytecode which is executed by the Java Virtual Machine.
Java Types: Java has two "categories" of types: primitive types and reference types.
Primitive Types:All the primitive types have specified sizes that are machine independent for portability.
This includes:
boolean same as bool in C++
char holds one 16 bit unicode character
byte 8-bit signed integer
short 16-bit signed integer
int 32-bit signed integer
long 64-bit signed integer
float floating-point number
double double precision floating-point number
Reference Types
Arrays classes
There are no struct, union, enum, unsigned, typedef, or pointers types in Java.
C++ Arrays vs Java Arrays: In C++, when you declare an array, storage for the array is allocated. In
Java, when you declare an array, you are really only declaring a pointer to an array; storage for the array
itself is not allocated until you use "new". This difference is elaborated as shown below:
C++
int A[10]; // A is an array of length 10
A[0] = 5; // set the 1st element of array A
JAVA
int [ ] A; // A is a reference to an array
A = new int [10]; // now A points to an array of length 10
A[0] = 5; // set the 1st element of the array pointed to by A
In both C++ and Java you can initialize an array using values in curly braces. Here's example Java code:
int [ ] myArray = {13, 12, 11};

In Java, you can copy an array using the arraycopy function. arraycopy is provided in java.lang.System,
so you must use the name System.arraycopy. The function has five parameters:
src: the source array (the array from which to copy)
srcPos: the starting position in the source array
dst: the destination array (the array into which to copy)
dstPos: the starting position in the destination array
count: how many values to copy
 the length of the source array must be at least srcPos+count
The arraycopy function also works when the source and destination arrays are the same array; so for
example, you can use it to "shift" the values in an array:
int [ ] A = {0, 1, 2, 3, 4};
System.arraycopy(A, 0, A, 1, 4);
After executing this code, A has the values: [0, 0, 1, 2, 3].

12
CS508 Final Term Preparation | Lecture 19 to 45

As in C++, Java arrays can be multidimensional. For example, a 2-dimensional array is an


array of arrays. However, a two-dimensional arrays need not be rectangular. Each row
can be a different length. Here's an example:
int [ ][ ] A; // A is a two-dimensional array
A = new int[5][]; // A now has 5 rows, but no columns yet
A[0] = new int [1]; // A's first row has 1 column
A[1] = new int [2]; // A's second row has 2 columns
A[2] = new int [3]; // A's third row has 3 columns
A[3] = new int [5]; // A's fourth row has 5 columns
A[4] = new int [5]; // A's fifth row also has 5 columns
C++ Classes vs Java Classes
In C++, when you declare a variable whose type is a class, storage is allocated for an object of that class,
and the class's constructor function is called to initialize that instance of the class. In Java, you are really
declaring a pointer to a class object; no storage is allocated for the class object, and no constructor
function is called until you use "new".
Java Classes:
MyClass m;
m = new MyClass();
Aliasing Problems in Java:The fact that arrays and classes are really pointers in Java can lead to some
problems. Here is a simple assignment that causes aliasing:
int [] A = new int [4];
Int [] B = new int [2];
This is depicted as below:

In Java, all parameters are passed by value, but for arrays and classes the actual parameter is really a
pointer, so changing an array element, or a class field inside the function does change the actual
parameter's element or field.
Type Conversion: Java is much stronger than C++ in the type conversions that are allowed.
Booleans cannot be converted to other types. For the other primitive types (char, byte, short, int, long,
float, and double), there are two kinds of conversion: implicit and explicit.
Implicit conversions:
An implicit conversion means that a value of one type is changed to a value of another type without any
special directive from the programmer.
char c = 'a';
int k = c;
long x = c;
float y = c;
double d = c;
Explicit conversions: Explicit conversions are done via casting: the name of the type to which you want a
value converted is given, in parentheses, in front of the value.

13
CS508 Final Term Preparation | Lecture 19 to 45

double d = 5.6; int k = (int)d; short s = (short)(d * 2.0);


JAVA CLASSES: Java classes contain fields and methods. A field is like a C++ data member, and a
method is like a C++ member function. Each field and method has an access level:
• private: accessible only in this class
• (package): accessible only in this package
• protected: accessible only in this package and in all subclasses of this class
• public: accessible everywhere this class is available

 In Java, all classes (built-in or user-defined) are (implicitly) subclasses of the class Object.
Constructor function:
As in C++, constructor functions in Java are used to initialize each instance of a class. They have no
return type (not even void) and can be overloaded; you can have multiple constructor functions, each
with different numbers and/or types of arguments. If you don't write any constructor functions, a
default (no-argument) constructor (that doesn't do anything) will be supplied.
For example:
this( 10 ); is a call to a constructor that expects one integer argument.
Initialization of fields: If you don't initialize a field (i.e., either you don't write any constructor
function, or your constructor function just doesn't assign a value to that field), the field will be given a
default value, depending on its type. The values are the same as those used to initialize newly created
arrays (see the "Java vs C++" notes).
Access Control: Note that the access control must be specified for every field and every method; there
is no grouping as in C++. For example, given these declarations:
public
int x;
int y;
only x is public; y gets the default, package access.
Static Fields and Methods: Fields and methods can be declared static. If a field is static, there is only
one copy for the entire class, rather than one copy for each instance of the class. (In fact, there is a copy
of the field even if there are no instances of the class.) A method should be made static when it does not
access any of the non-static fields of the class, and does not call any non-static methods. (In fact, a static
method cannot access non-static fields or call non-static methods.)
Final Fields and Methods:Fields and methods can also be declared final. A final method cannot be
overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be
assigned to again.
Some Useful Built-in Classes: Following is a list of some useful classes in Java. These classes are not
really part of the language; they are provided in the package java.lang
1. String
•String Creation:
String S1 = "hello",
•String concatenation
String S1 = “hello ” + “world”;
2. Object
Object is the Base class for all Java Classes.

14
CS508 Final Term Preparation | Lecture 19 to 45

3. Classes for primitive types


In Java, we have classes also for primitive types. These are: Boolean, Integer, Double,
etc. Note that variable of bool, int, etc types are not objects whereas variable of type
Boolean, Integer, etc are objects.
Packages: Every class in Java is part of some package. All classes in a file are part of the same package.
You can specify the package using a package declaration:
package name ;
You can access public classes in another (named) package using:
package-name.class-name
You can access the public fields and methods of such classes using:
package-name.class-name.field-or-method-name

 You must still use the class-name to access the classes in the packages, and class-name.field-or-
method-name to access the fields and methods of the class; the only thing you can leave off is
the package name.
Inheritance: Java directly supports single inheritance. To support concept of a interface class is used.
Inheritance is achieved as shown below:
class SuperClass {

}
class SubClass extends SuperClass {

}
overloaded: If the subclass defines a method with the same name, but with a different number of
arguments or different argument types, then the subclass has two methods with that name: the old one
defined by the superclass, and the new one it defined.
Overridden: If the subclass defines a method with the same name, and the same number and types of
arguments, then the subclass has only one method with that name: the new one it defined. A method
cannot be overridden if it is defined as final in the superclass.
Dynamic Binding:In C++, a method must be defined to be virtual to allow dynamic binding. In Java all
method calls are dynamically bound unless the called method has been defined to be final, in which case
it cannot be overridden and all bindings are static.
Constructors
A subclass's constructors always call a super class constructor, either explicitly or implicitly.
Abstract Classes
An abstract method is a method that is declared in a class, but not defined.
Interface
As mentioned earlier, multiple inheritance is achieved through Interface in Java. A class can implement
one or more interfaces.
Exception Handling in Java: java exceptions are objects of classes that are descendents of Throwable
class. There are two predefined subclasses of Throwable: Error and Exception.
There are two predefined descendents of Exception: IOException and RuntimeException. IOException
deals with errors in I/O operation.

15
CS508 Final Term Preparation | Lecture 19 to 45

In the case of RuntimeException there are some predefined exceptions which are, in many cases,
thrown by JVM for errors such as out of bounds, and Null pointer.

Checked and Unchecked Exceptions:Exceptions of class Error and RuntimeException are called
unchecked exceptions. They are never a concern of the compiler. A program can catch unchecked
exceptions but it is not required. All other are checked exceptions. Compiler ensures that all the checked
exceptions a method can throw are either listed in its throws clause or are handled in the method.
Exception Handlers
Exception handler in Java is similar to C++ except that the parameter of every catch must be present and
its class must be descendent of Thrwoable. The syntax of try is exactly same as C++ except that there is
finally clause as well.

 throws clause is overloaded in C++ and conveys two different meanings: one as specification and
the other as command.
 A finally clause is usually included to make sure that some clean-up (e.g., closing opened files) is
done.
Java Threads
Java supports concurrency through threads which are lightweight processes. A thread is similar to a real
process in that a thread and a running program are threads of execution. A thread takes advantage of
the resources allocated for that program instead of having to allocate those resources again.
Creating Java Threads: There are two ways to create our own Thread object:
1. Subclassing the Thread class and instantiating a new object of that class
2. Implementing the Runnable interface
Starting the Threads
A thread is started by simply sending the start message to the thread.
Thread Methods
Some of the common thread methods are listed below:
• start()
• sleep()

16
CS508 Final Term Preparation | Lecture 19 to 45

• yield()
• run()
• wait()
• notify()
• notifyAll()
• setPriority()
Thread Synchronization - Wait and Notify
Threads are based upon the concept of a Monitor. The wait and notify methods are used just like wait
and signal in a Monitor. They allow two threads to cooperate and based on a single shared lock object.
notify and notifyAll
There is a slight difference between notify and notifyAll. As the name suggest, notify() wakes up a single
thread which is waiting on the object's lock. notifyAll() wakes up ALL waiting threads; the scheduler
decides which one will run.
Applet
Java also has support for web applications through Applets. An applet is a stand alone
Java application. Java applet runs in a Java-enabled Web browser.

Lecture 31 to 34:
C# was released by Microsoft in June 2000 as part of the .Net framework. It was co-authored by Anders
Hejlsberg (who is famous for the design of the Delphi language), and Scott Wiltamuth. C# is a strongly-
typed object-oriented language. It is Similar to Java and C++ in many respects. The .NET platform is
centered on a Common Language Runtime (CLR - which is similar to a JVM) and a set of libraries which
can be exploited by a wide variety of languages which are able to work together by all compiling to an
intermediate language (IL).
Java and C# - Some Commonalities
 Both support concurrency through thread support by putting a lock on objects when
entering code marked as locked/synchronized.
 Both have single inheritance and support for interfaces.
 The "." operator is always used and there are no more ->, :: operators.
 null and boolean/bool are keywords.
 All values must be initialized before use.
Some C# features which are different from Java:
 C# has the concept of 'delegates' which are type-safe method pointers and are used to
implement event-handling
 It supports three types of arrays: single dimensional, multi-dimensional rectangular and
multi-dimensional jagged arrays
 It also has support for class 'properties'.
C# Hello World: Let us have a look at the Hello World Program in C#.
using System; // System namespace
public class HelloWorld
{
public static void Main() // the Main function starts

17
CS508 Final Term Preparation | Lecture 19 to 45

// with capital M
{
Console.WriteLine("Hello World!”);
}
}
Variable Types: Reference Types and Value Types:
As mentioned earlier, C# is a type-safe language. Variables can hold either value types or reference
types, or they can be pointers. When a variable v contains a value type, it directly contains an object
with some value and when it contains a reference type, what it directly contains is something which
refers to an object.
Built-in Types: The following table lists the built-in C# types and their ranges.

Structs:
1. Java did not have structs which have been brought back by C#. However, as compared to C++,
they are significantly different in C#.
2. Structs cannot declare a default (parameterless) constructor.
3. Structs are more efficient than classes, that’s’ why they are perfect for the creation of
lightweight objects.
Properties
C# has formalized the concept of getter/setter methods. The relationship between a get and set method
is inherent in C#, while has to be maintained in Java or C++. For example, in Java/C++ we will have to
write code similar to the one shown below:
public int getSize() {
return size;

18
CS508 Final Term Preparation | Lecture 19 to 45

}
public void setSize (int value) {
size = value;
}
foo.setSize (getSize () + 1);
Reference types: In C#, the pre-defined reference types are object and string. Reference types actually
hold the value of a memory address occupied by the object they reference.
Reference types however suffer from the problem of aliasing as shown below:
object x = new object();
x.myValue = 10;
object y = x;
y.myValue = 20; // after this statement both x.myValue and y.myValue
// equal 20
Pointers: Pointers were present in C++ but Java designers took them out. C# has brought them back.
However, C#, pointers can only be declared to hold the memory addresses of value types. That is, we
cannot have pointers for reference types. The rest is very similar to C++. This is illustrated with the help
of the following example:
int i = 5;
int *p;
p = &i; // take address of i
*p = 10; // changes the value of i to 10
One major difference between C++ and C# is that the ‘*’ applies to the type. That is, as opposed to C++,
in C#, the following statement would declare two pointers p1 and p2:
int * p1, p2;
Just like C++, the dereference operator ‘->’ is used to access elements of a struct type.
Pointers and unsafe code: In C#, we have two modes for the code, the managed and unmanaged. These
are elaborated as below:
Managed code:
1. Managed code is executed under the control of Common Language Runtime (CRL).
2. It has automatic garbage collection. That is, the dynamically allocated memory area which is no longer
is in use is not destroyed by the programmer explicitly. It is rather automatically returned back to heap
by the built-in garbage collector.
3. There is no explicit memory’s allocation and deallocation and there is no explicit calls to the garbage
collector i.e. call to destructor.
Unmanaged code (Java does not have this concept): The unmanaged code provides access to memory
through pointers just like C++. It is useful in many scenarios. For example:
• Pointers may be used to enhance performance in real time applications.
• External Functions: In non-.net DLLs some external functions requires a pointer as a parameter, such
as Windows APIs that were written in C.
• Debugging: Sometimes we need to inspect the memory contents for debugging purposes, or you
might need to write an application that analyzes another application process and memory.
Unsafe: The keyword unsafe is used while dealing with pointer. The name reflects the risks that you
might face while using it. We can declare a whole class as unsafe as shown below:
unsafe class Class1 {

19
CS508 Final Term Preparation | Lecture 19 to 45

//you can use pointers here!


}
Disadvantages of using unsafe code in C#:
• Complex code
• Harder to use
• Pointers are harder to debug
• You may compromise type safety
• Misusing might lead to the followings:
o Overwrite other variables
o Illegal access to memory areas not under your control
o Stack overflow
Garbage Collector Problem in C# and the fixed keyword:
When pointers are used in C#, Garbage collector can change physical position of the objects. If garbage
collector changes position of an object the pointer will point at wrong place in memory. To avoid such
problems C# contains ‘fixed’ keyword – informing the system not to relocate an object by the garbage
collector.
Arrays: Arrays in C# are more similar to Java than to C++. We can create an array as did in Java by using
the new operator. Once created, the array can be used as usual as shown below:
int[] i = new int[2];
i[0] = 1;
i[1] = 2;
By default all arrays start with their lower bound as 0.
Types of Arrays:
• Single Dimensional Arrays
• Multidimensional arrays
o Rectangular
o Jagged
Rectangular Arrays: A rectangular array is a single array with more than one dimension, with the
dimensions' sizes fixed in the array's declaration. Here is an example:
int[,] squareArray = new int[2,3];
Jagged Arrays (Similar to Java jagged arrays): Jagged arrays are multidimensional arrays with irregular
dimensions. This flexibility derives from the fact that multidimensional arrays are implemented as arrays
of arrays.
int[][] jag = new int[2][];
jag[0] = new int [4];
jag[1] = new int [6];
Each one of jag[0] and jag[1] holds a reference to a single-dimensional int array.
Pointers and Arrays: Just as in C++, a pointer can be declared in relation to an array:
int[] a = {4, 5};
int *b = a;
In the above example memory location held by b is the location of the first type held by a. This
first type must, as before, be a value type. If it is reference type then compiler will give error.
Enumerations:C# brought back enumerations which were discarded by Java designers.
However, they are slightly different from C++.

20
CS508 Final Term Preparation | Lecture 19 to 45

• An enumeration is a special kind of value type limited to a restricted and unchangeable set of
numerical values.
• By default, these numerical values are integers, but they can also be longs, bytes, etc. (any
numerical value except char) as will be illustrated below.
• Type safe
• Consider the following example:
public enum DAYS {
Monday=1,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Boolean
• In C#, Boolean values do not convert to integers and Boolean values (true, false) do not
equate to integer variables. Thus, you may not write:
if ( someFuncWhichReturnsAnIntegerValue() )
• No arithmetic expression is allowed where Boolean expressions are expected. Thus, if you
write:
if (x = y) // compilation error
It will not be compiled.
Operator evaluation order:As discussed earlier, in C/C++ the operator evaluation order is not
specified. We have discussed at length how that creates problems. In C#, it is strictly from left
to right and hence there is no ambiguity.
For example,
a=5;
x=a++ + --a;
If evaluated left-to-right
x=10
If evaluated right-to-left
x=8
Loops: C# provides a number of the common loop statements. These include while, do-while,
for, and foreach.
foreach loop: The 'foreach' loop is used to iterate through the values contained by any object which
implements the IEnumerable interface. It has the following syntax:
foreach (variable1 in variable2) statement[s]
Switch statement: They are more or less similar to their counterparts in C++. The switch statement is
however significantly different is explained below. The syntax of the switch statement is given below:
switch (expression)

21
CS508 Final Term Preparation | Lecture 19 to 45

{
case constant-expression:
statements
jump statement
[default:
statements
jump statement
]
}
example:
switch(a){
case 2:
Console.WriteLine("a>1 and ");
goto case 1;
case 1:
Console.WriteLine("a>0");
break;
default:
Console.WriteLine("a is not set");
break;
}
Class
1. Class Attributes:
• Attributes are used to give information to .Net compiler
o E.g. it is possible to tell the compiler that a class is compliant with >Net
Common Language Specification.
[CLSCompliant (true)]
publc class MyClass
{
//class code
}
2. Class Modifiers
Support for OOP is provided through classes. In C#, we have the following modifiers:
• public: same as C++
• internal: internal is accessible only to types within the same assembly which is similar to
package in Java.
• protected: same as C++
• internal protected: protected within the same assembly
• private: same as C++
• new:
– The 'new' keyword can be used for 'nested' classes.
– A nested class is one that is defined in the body of another class; it is in most ways identical to
a class defined in the normal way, but its access level cannot be more liberal than that of the
class in which it is defined.

22
CS508 Final Term Preparation | Lecture 19 to 45

abstract: A class declared as 'abstract' cannot itself be instanced - it is designed only to be a base class
for inheritance.
sealed: A class declared as 'sealed' cannot be inherited from. It may be noted that structs can also not
be inherited from. But it can inherit from other class.
Method Modifiers: C# provides the following methods modifiers:
• static: The 'static' modifier declares a method to be a class method.
• new, virtual, override:
• extern: Similar to C extern. Mean that the method is defined externally, using a language other than
C#
Hiding and Overriding: The main difference between hiding and overriding relates to the choice of
which method to call where the declared class of a variable is different to the run-time class of the
object it references.
Method Hiding: A 'new' method only hides a super-class method with a scope defined by its access
modifier. In this case method calls do not always 'slide through' in the way that they do with virtual
methods. So, if we declare two variables thus if we have:
Square sq = new Square(4);
Rectangle r = sq;
Method parameters: public void foo(int x, ref int y)
Out Parameters: C# requires definite assignment, which means that the local variables, a, and b must be
initialized before foo is called.
int a, b;
b = 0;
someObject.f00(ref a, b); // not allowed
// a has not been
// initialized
a = 0; b =0;
someObject.f00(ref a, b); // now it is OK
params: One can pass an arbitrary number of types to a method by declaring a parameter array with the
'params' modifier. Types passed as 'params' are all passed by value.
Readonly fields: Readonly field are instance fields that cannot be assigned to. That is, their value is
initialized only once and then cannot be modified. This is shown in the following example:
class Pair
{
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
public void Reset()
{
x = 0; // compile time errors
y = 0;
}
private readonly int x, y; // this declares Pair as an immutable read only object

23
CS508 Final Term Preparation | Lecture 19 to 45

}
is operator:
• The ‘is’ operator supports run time type information.
• It is used to test if the operator/expression is of certain type
o Syntax: expression is type
• Evaluates to a Boolean result.
• It can be used as conditional expression.
• It will return true
o if the expression is not NULL
o the expression can be safely cast to type.
as operator:
• The as operator attempts to cast a given operand to the requested type.
o Syntax: expression as type
• The normal cast operation – (T) e – generates an InvalidCastException when there is no valid
cast.
• The as operator does not throw an exception; instead the result returned is null as shown
o expression is type ? (type) expression : (type) null
new operator
• In C++, the new keyword instantiates an object on the heap.
• In C#, with reference types, the new keyword does instantiate objects on the heap but with
value types such as structs, the object is created on the stack and a constructor is called.
• You can, create a struct on the stack without using new, but be careful! New initializes the
object.
• If you don't use new, you must initialize all the values in the struct by hand before you use it
(before you pass it to a method) or it won't compile.
Boxing: Boxing is converting any value type to corresponding object type and convert the resultant
'boxed' type back again.
int i = 123;
object box = i; // value of i is copied to the object box
if (box is int) // runtime type of box is returned as boxed value type
{
Console.Write("Box contains an int"); // this line is printed
}
Interfaces
• Just like Java, C# also has interfaces contain method signatures.
• There are no access modifier and everything is implicitly public.
• It doest not have any fields, not even static ones.
• A class can implement many interfaces but unlike Java there is no implements keyword .
• Syntax notation is positional where we have base class first, then base interfaces as shown
below:
o class X: CA, IA, IB
{

}

24
CS508 Final Term Preparation | Lecture 19 to 45

Delegates are reference types which allow indirect calls to methods. A delegate instance holds
references to some number of methods, and by invoking the delegate one causes all of these methods
to be called.
Exception Handling and Multithreading
Exception handling is similar to java but is less restrictive. Multithreading is similar to java.

Lecture 35 to37:
PHP – Personal Home Page: A Server-side Scripting Programming Language
What is PHP?
PHP stands for “PHP: Hypertext Preprocessor”. It is a server-side scripting language. PHP scripts are
executed on the server and it is especially suited for Web development and can be embedded into
HTML. PHP is an open source software (OSS) and is free to download and use.
What is a PHP File?: PHP files may contain text, HTML tags and scripts. PHP files are returned to the
browser as plain HTML. PHP files have a file extension of ".php", ".php3", or ".phtml". You need three
things to make this work: the PHP parser (CGI or server module), a web server and a web browser.
PHP Hello World: Following is the PHP Hello World program.
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php // start of php code
echo '<p>Hello World</p>';
?>
</body>
</html>
 It may be noted that PHP supports C++ type of comments and requires a semicolon “;” at the
end of each statement.
PHP Opening and Closing Tags: PHP scripts are always enclosed in between two PHP tags. This tells your
server to parse the information between them as PHP. The three different forms are as follows:
1. <?php
echo “this is the recommended style”;
?>
2. <script language="php">
echo “this style is also available”;
</script>
3. <?
echo “this is short tags style; it needs to be configured”;
?>
There is also another form which may or may not be supported on some browsers. It is shown as below:
4. <%
echo ‘this is ASP-style tags; it may not be available';
%>

25
CS508 Final Term Preparation | Lecture 19 to 45

Data types:The type of a variable is decided at runtime by PHP depending on the context in which that
variable is used. PHP supports the following data types:
• Boolean
• integer
• float or double
• string
• array
• object
• resource
• NULL
Integers:
The size of an integer is platform-dependent, although a maximum value of about two billion is the
usual value (that's 32 bits signed). 2147483647 = 231 – 1. PHP does not support unsigned integers.
Strings
PHP strings are created using single quote or double quote. They can also be created by
<<< which is called heredoc.
Variable: Variables in PHP are represented by a dollar sign followed by the name of the variable. The
variable name is case-sensitive. A valid variable name starts with a letter or underscore, followed by any
number of letters, numbers, or underscores.
String conversion to numbers
When a string is evaluated as a numeric value, the resulting value and type are determined as follows.
• The string will evaluate as a float if it contains any of the characters '.', 'e', or 'E'.
Otherwise, it will evaluate as an integer.
• The value is given by the initial portion of the string. If the string starts with valid
numeric data, this will be the value used. Otherwise, the value will be 0 (zero).
Arrays: An array in PHP is an ordered map. An array can be created by the array() construct. It
takes a certain number of comma-separated key => value pairs. key may be an integer or string.
The following example illustrates this concept:
<?php
$arr = array("foo" => "bar", 12 => true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
Class: A class is defined as shown below:
<?php
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item($artnr, $num) {
$this->items[$artnr] += $num;
}
function remove_item($artnr, $num) {

26
CS508 Final Term Preparation | Lecture 19 to 45

if ($this->items[$artnr] > $num) {


$this->items[$artnr] -= $num;
return true;
}
elseif ($this->items[$artnr] == $num) {
unset($this->items[$artnr]);
return true;
}
else { return false; }
}
}
?>
Aliasing: Aliasing is used to assign by reference. To assign by reference, simply prepend an
ampersand (&) to the beginning of the variable which is being assigned (the source variable) as
shown below:
<?php
$foo = ‘Fakhar';
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.
?>
Variable variable
A variable variable is like pointers that is, it maintains the address of a variable in it.
Constants
A constant is an identifier (name) for a simple value that cannot change during the execution of
the script. A constant is case-sensitive by default.
Logical operators:PHP supports the following logical operators.
and, or, xor, !, &&, ||
The reason for the two different variations of "and" and "or" operators is that they operate at
different precedence. This is demonstrated with the help of the following example:
$a and $b or $c // ($a and $b) or $c
$a && $b || $c
$a and $b || $c // $a and ($b || $c)
String operators: There are two string operators. The first is the concatenation operator ('.'),
which returns the concatenation of its right and left arguments. The second is the
concatenating assignment operator ('.='), which appends the argument on the right side to the
argument on the left side.
<?php
$a = "Hello ";

27
CS508 Final Term Preparation | Lecture 19 to 45

$b = $a . "World!"; // now $b contains "Hello World!"


$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
Array Operators: PHP provides a number of operators to manipulate arrays. These are:
• $a + $b Union – Union of $a and $b.
• $a == $b Equality – TRUE if $a and $b have the same key/value pairs.
• $a === $b Identity - TRUE if $a and $b have the same key/value pairs in the same
order and of the same types.
• $a != $b Inequality - TRUE if $a is not equal to $b.
• $a <> $b Inequality - TRUE if $a is not equal to $b.
• $a !== $b Non-identity - TRUE if $a is not identical to $b.
Control Statements: PHP supports the following control statements:
• if
• while
• do while
• for
• switch
• foreach
• break
• continue
If statements
<?php
if ($a > $b) { echo "a is bigger than b"; }
elseif ($a == $b) { echo "a is equal to b"; }
else { echo "a is smaller than b"; }
?>
Foreach: foreach statement works only on arrays, and will issue an error when you try to use it
on a variable with a different data type or an uninitialized variable. It gives an easy way to
iterate over arrays. There are two syntaxes; the second is a minor but useful extension of the
first:
• foreach (array_expression as $value) statement
• foreach (array_expression as $key => $value) statement
Each: each return the current key and value pair from an array and advance the array cursor. It
is used in the following manner:
array each ( array &array )
break: break ends execution of the current for, foreach, while, do-while or switch structure. In
PHP, break accepts an optional numeric argument which tells it how many nested enclosing
structures are to be broken out of. The following example illustrates this concept:
<?php

28
CS508 Final Term Preparation | Lecture 19 to 45

$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5<br />\n";
break 1; // Exit only the switch.
case 10:
echo "At 10; quitting<br />\n";
break 2; // Exit the switch and the while.
default:
break; // Exit only the switch.
}
}
?>
Continue: continue is used within looping structures to skip the rest of the current loop
iteration and continue execution at the condition evaluation and then the beginning of the next
iteration. Note: Note that in PHP the switch statement is considered a looping structure for the
purposes of continue.
<?php
for ($i = 0; $i < 5; ++$i) {
if ($i == 2) continue print "$i\n";
}
?>
Alternative syntax for control statements
<?php
if ($a == 5):
echo "a equals 5";
echo "...";
elseif ($a == 6):
echo "a equals 6";
echo "!!!";
else: echo "a is neither 5 nor 6";
endif;
?>
User defined functions
<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>

29
CS508 Final Term Preparation | Lecture 19 to 45

PHP also allows functions to be defined inside functions.


Function arguments
PHP supports passing arguments by value (the default), passing by reference, and default argument
values.
Classes and Objects: Classes and objects are similar to Java. A variable of the desired type is created
with the new operator. It supports Single inheritance only and uses the keyword extends to inherit from
a super class.
Databases: One of the strongest features of PHP is its support for providing web pages access to
database.

Lecture #38: JavaScript:


Inclusion of language attribute
<script language=“VBS”>….</script>
Inclusion of type attribute
<script type=“text/javascript”>….</script>
The type attribute is W3C recommended, it makes the language more common and in many ways more
useful
<script> tag is used to delimit the script code from the HTML
ƒ The script tag causes the browser’s JavaScript interpreter to be invoked, the script run and any
output produced
ƒ The browser is considered the “host” environment
ƒ There are other hosts for JavaScript and its variants
Location of Code: JavaScript may be placed at three places
In the <head> element
Place scripts to be called or when event is triggered here
Ensures script is loaded before called
<html>
<head>
<script type=“text/javascript”>
//script statements
</script>
</head>
In the <body> element
Place scripts to be executed when the page loads here
Script generates some or all of the contents of the page
<body>
<script type=“text/javascript”>
//script statements
</script>
</body>
External to the HTML file
<head>
<script src=“myfile.js”>
</script>

30
CS508 Final Term Preparation | Lecture 19 to 45

</head>
Could be in <head> or <body>
External script should not contain <script> tag

Statements
• A script is made up of individual statements
• Javascript statements are terminated by returns or semi-colons same as
• So, prefer to use semi-colons
x=x+1 alert(x) //throws an error while
x=x+1; alert(x); //does not
• Every variable has a data type that indicates what kind of data the variable holds
• Basic data types in JavaScript
• Strings
Strings may include special escaped characters
• Numbers (integers, floats)
• Booleans (true, false)
• ‘null’ and ‘undefined’ are also considered as types

 JavaScript is a weekly typed language meaning that the contents of a variable can change from
one type to another
• Example
x = “hello”; x = 5; x=false;
While week typing seems beneficial to a programmer it can lead to problems
Arrays
• An ordered set of values grouped together with a single identifier
• Defining Arrays
• var myArray = [1,5,1968,3];
• var myArray2 = [“fakhar”,true,3,-47.2];
• var myArray3 = new Array ();
• var myArray4 = new Array (10);
Arrays

31
CS508 Final Term Preparation | Lecture 19 to 45

• Arrays in JavaScript are 0 based


• We access arrays by index values
• var myArray = [1,5,1968,3];
• myArray[3] is ‘3’
Operators
• Basic Arithmetic
+,-,/,*,%
• Increment decrement
++, - -
• Comparison
< , > , >= , <= , != , == , === (type equality)
• Logical
&&, ||, !
• Bitwise Operators
&,|,^
• String Operator
• + (used for concatenation)
• document.write(“JavaScript” + “is” + “great!”);
Type Conversion
• Converting one type of data to another is both useful and a source of numerous errors in
JavaScript
• var x = “10” – 2 ; //result is 8
• var x = “2” – “2” ; //result is 0
• var x = “2” + “2” ; //result is “22”
Control Statements
• If
• Switch
• While
• Do-while
• For
• Continue
• Break
• For (in)

Lecture #39: JavaScript:


Objects
• An object is a collection of data types as well as functions in one package
• The various data types called properties and functions called methods are accessed using the
dot notation
• objectname.propertyname
Objects
• There are many types of objects in JavaScript
ƒ Built-in objects (primarily type related)
ƒ Browser objects (navigator, window etc.)

32
CS508 Final Term Preparation | Lecture 19 to 45

ƒ Document objects (forms, images etc.)


ƒ User defined objects
Two Object Models: In JavaScript, two primary object models are employed
• Browser Object Model (BOM)
ƒ The BOM provides access to the various characteristics of a browser such as the browser
window itself, the screen characteristics, the browser history and so on.
• Document Object Model (DOM)
ƒ The DOM on the other hand provides access to the contents of the browser window, namely
the documents including the various HTML elements ranging from anchors to images as well as
any text that may be enclosed by such element.

33
CS508 Final Term Preparation | Lecture 19 to 45

34
CS508 Final Term Preparation | Lecture 19 to 45

35
CS508 Final Term Preparation | Lecture 19 to 45

Lecture #40:
Names
• Design issues:
ƒ Maximum length?
ƒ Are connector characters allowed?
ƒ Are names case sensitive?
ƒ Are special words reserved words or keywords?
Special Words
• There are two types of special words
ƒ Keyword
ƒ Reserved word
• A keyword is a word that is special only in a certain context
ƒ REAL X

36
CS508 Final Term Preparation | Lecture 19 to 45

ƒ REAL = 44.7
• Disadvantage: poor readability
• A reserved word is a special word that cannot be used as a user-defined name
ƒ Type
• Type: Determines the range of values of variables and the set of operations that are defined for values
of that type; in the case of floating point, type also determines the precision
ƒ Value
• Value: The contents of the location with which the variable is associated
ƒ Binding
• Binding : A binding is an association, such as between an attribute and an entity, or between an
operation and a symbol
ƒ Binding Time: It is the time at which a binding takes place
Possible binding times
1. Language design time - e.g. bind operator symbols to operations
2. Language implementation time - e.g. bind fl. pt. type to a representation
3. Compile time - e.g. bind a variable to a type in C or Java
4. Load time- e.g.
5. Runtime - e.g. bind a non-static local variable to a memory cell

37
CS508 Final Term Preparation | Lecture 19 to 45

• Disadvantage
ƒ Lack of flexibility (no recursion)
Stack Dynamic Variables:
• Bound to storages when execution reaches the code to which the declaration is attached. (But,
data types are statically bound.) That is, stack-dynamic variables are allocated from the run-time stack.
• Example
o E.g. a Pascal procedure consists of a declaration section and a code section.
o E.g. FORTRAN 77 and FORTRAN 90 use SAVE list for stack-dynamic list.
o E.g. C and C++ assume local variables are static-dynamic.
• Advantage
o allows recursion; conserves storage
• Disadvantages
o Overhead of allocation and deallocation
o Subprograms cannot be history sensitive
o Inefficient references (indirect addressing)
Explicit Heap Dynamic Variables
• Allocated and de-allocated by explicit directives, specified by the programmer, which take
effect during execution
• Referenced only through pointers or references
• Examples
ƒ Dynamic objects in C++ (via new and delete)
ƒ All objects in Java
• Advantage
ƒ Provide dynamic storage management
• Disadvantage
ƒ Inefficient and unreliable
Implicit Heap Dynamic Variables
• Allocation and de-allocation is caused by assignment statements
• Example
ƒ All variables in SNOBOL
• Advantage
ƒ Flexibility
• Disadvantages
ƒ Inefficient, because all attributes are dynamic
ƒ Loss of error detection

38
CS508 Final Term Preparation | Lecture 19 to 45

Lecture #41: Type Checking


• Generalizes the concept of operands and operators to include subprograms and assignments
• Type checking is the activity of ensuring that the operands of an operator are of compatible
types
• A compatible type is one that is either legal for the operator, or is allowed under language
rules to be implicitly converted, by compiler generated code, to a legal type. This automatic
conversion is called coercion
• A type error is the application of an operator to an operand of an inappropriate type
• If all type bindings are static, nearly all type checking can be static
• If type bindings are dynamic, type checking must be dynamic
• A programming language is strongly typed if type errors are always detected
• A programming language which does all the type checking statically then it is a strongly typed
languages otherwise weakly typed language.
Strongly Typed Languages?
• FORTRAN 77 is not strongly typed
ƒ Parameters, EQUIVALENCE
• C and C++ are not
ƒ Parameter type checking can be avoided
ƒ Unions are not type checked
• Pascal is not
ƒ Variant records
• Modula-2 is not
ƒ Variant records
• Ada is, almost
ƒ UNCHECKED CONVERSION is a loophole
ƒ Coercion rules strongly affect strong typing; they can weaken it considerably (C++
versus Ada)
• Advantage of strong typing
ƒ Allows the detection of the misuse of variables that result in type errors
Type Compatibility
• Type compatibility by name means that the two variables have compatible types if they are in
either the same declaration or in declarations that use the same type name
• Easy to implement but highly restrictive
ƒ Sub ranges of integer types are not compatible with integer types
Data Types
• Design Issues
ƒ What is the syntax of references to variables?
ƒ What operations are defined and how are they specified?
Primitive Data Types
• Not defined in terms of other data types
1. Integer
ƒ Almost always an exact reflection of the hardware, so the mapping is trivial
ƒ There may be as many as eight different integer types in a language
2. Floating Point

39
CS508 Final Term Preparation | Lecture 19 to 45

ƒ Models real numbers, but only as approximations


ƒ Languages for scientific use support at least two floating-point types; sometimes more
ƒ Usually exactly like the hardware, but not always; some languages allow accuracy specs in code
e.g. (Ada)
type SPEED is digits 7 range 0.0..1000.0;
type VOLTAGE is delta 0.1 range -12.0..24.0;
3. Decimal
ƒ For business applications (money)
ƒ Store a fixed number of decimal digits
ƒ Advantage
Accuracy
ƒ Disadvantages
Limited range, wastes memory
ƒ COBOL and ADA supports decimal
ƒ C++ and java does not support decimal
4. Boolean
ƒ Could be implemented as bits, but often as bytes
ƒ Advantage
Readability
Character String Types
ƒ Values are sequences of characters
ƒ Design issues:
Is it a primitive type or just a special kind of array?
Is the length of objects static or dynamic?
ƒ Operations:
Assignment
Comparison (=, >, etc.)
Concatenation
Substring reference
Pattern matching

40
CS508 Final Term Preparation | Lecture 19 to 45

Ordinal Types (user defined)


ƒ An ordinal type is one in which the range of possible values can be easily associated with the
set of positive integers
ƒ Enumeration Types - one in which the user enumerates all of the possible values, which are
symbolic constants
ƒ Design Issue
Should a symbolic constant be allowed to be in more than one type definition?
ƒ Examples
Pascal
▪ Cannot reuse constants
▪ They can be used for array subscripts e.g. for variables, case selectors
▪ NO input or output
▪ Can be compared
Ada
▪ Constants can be reused (overloaded literals)
▪ Disambiguates with context or type_name
▪ CAN be input and output
C and C++
▪ Like Pascal, except they can be input and output as integers
Java does not include an enumeration types
C# includes them
Arrays
ƒ An array is an aggregate of homogeneous data elements in which an individual element is
identified by its position in the aggregate, relative to the first element
ƒ Design Issues
What types are legal for subscripts?
Are subscripting expressions in element references range checked?
When are subscript ranges bound?
When does allocation take place?
What is the maximum number of subscripts?
Can array objects be initialized?
Subscript Types
ƒ FORTRAN, C, C++
int only
ƒ Pascal
Any ordinal type (int, boolean, char, enum)
ƒ Ada
int or enum (includes boolean and char)
ƒ Java
integer types only
Four Categories of Arrays (based on subscript binding and binding to storage)
ƒ Static - range of subscripts and storage bindings are static e.g. FORTRAN 77, some arrays in Ada
Advantage: execution efficiency (no allocation or de-allocation)

41
CS508 Final Term Preparation | Lecture 19 to 45

ƒ Fixed stack dynamic - range of subscripts is statically bound, but storage is bound at
elaboration time e.g. C local arrays are not static
Advantage: space efficiency
ƒ Stack-dynamic - range and storage are dynamic, but fixed from then on for the variable’s
lifetime e.g. Ada declare blocks declare
STUFF : array (1..N) of FLOAT;
begin
...
end;
Advantage: flexibility - size need not be known until the array is about to be used

Lecture 42: Records-(like structs in C/C++):


Description:
- Are composite data types like arrays
- The difference between array and record is that array elements are of same data type where
as record is a logical grouping of heterogeneous data elements.
- Another difference is that access to array elements is much slower than access to record fields,
because subscripts are dynamic (field names are static)
- Dynamic subscripts could be used with record field access, but it would disallow type checking
and it would be much slower
Design Issues:
- What is the form of references?
- What unit operations are defined?
Record Definition Syntax
- COBOL uses level numbers to show nested records; others use recursive definitions
- Examples:
COBOL
field_name OF record_name_1 OF ... OF
record_name_n
Others (dot notation)
record_name_1.record_name_2. ...
.record_name_n.field_name
- Better Approach:
According to readability point of view COBOL record definition syntax is easier to read
and understand but according to writability point of view other languages record
definition syntax is easier to write and less time consuming.
Record Field References
- Two types of record field references:
Fully qualified references must include all record names
Elliptical references allow leaving out record names as long as the reference is unambiguous
- Pascal and Modula-2 provide a with clause to abbreviate references
Record Operations
- Assignment
Pascal, Ada, and C allow it if the types are identical

42
CS508 Final Term Preparation | Lecture 19 to 45

In Ada, the RHS can be an aggregate constant


- Initialization
- Allowed in Ada, using an aggregate constant
- Comparison
- In Ada, = and /=; one operand can be an aggregate constant
Pointers
ƒ Description:
- A pointer type is a type in which the range of values consists of memory addresses and a
special value, nil (or null)
ƒ Uses:
- Addressing flexibility
- Dynamic storage management
ƒ Fundamental Pointer Operations:
- Assignment of an address to a pointer
- References (explicit versus implicit dereferencing)
ƒ Design Issues
- What is the scope and lifetime of pointer variables?
- What is the lifetime of heap-dynamic variables?
- Are pointers restricted to pointing at a particular type?
- Are pointers used for dynamic storage management, indirect addressing, or both?
- Should a language support pointer types, reference types, or both?
- Pointer arithmetic?
ƒ Problems with Pointers
- Dangling pointers
A pointer points to a heap-dynamic variable that has been deallocated
- Lost Heap-Dynamic Variables
A heap-dynamic variable that is no longer referenced by any program pointer
The process of losing heap-dynamic variables is called memory leakage
- Pointers are like goto's - they widen the range of cells that can be accessed by a variable
Unions
ƒ Description:
- A union is a type whose variables are allowed to store different type values at different times
during execution
ƒ Design Issues for unions:
- What kind of type checking, if any, must be done?
- Should unions be integrated with records?
Arithmetic Expressions
ƒ Description:
- Arithmetic evaluation was one of the motivations for the development of the first
programming languages
- Arithmetic expressions consist of operators, operands, parentheses, and function calls
- 15 * (a + b) / log(x)
ƒ Design issues for arithmetic expressions:
- What are the operator precedence rules?

43
CS508 Final Term Preparation | Lecture 19 to 45

- What are the operator associativity rules?


- What is the order of operand evaluation?
- Are there restrictions on operand evaluation side effects?
- Does the language allow user-defined operator overloading?
- What mode mixing is allowed in expressions?
- Conditional expressions?

Lecture #43:
Arithmetic Expressions: Operators
- A unary operator has one operand
- A binary operator has two operands
- A ternary operator has three operands
Arithmetic Expressions: Operator Precedence Rules
- The operator precedence rules for expression evaluation define the order in which “adjacent”
operators of different precedence levels are evaluated
- Typical precedence levels
parentheses
unary operators
** (if the language supports it)
*, /
+, -
Arithmetic Expressions: Potentials for Side Effects
- Functional side effects: when a function changes a two-way parameter or a non-local variable
- Problem with functional side effects:
When a function referenced in an expression alters another operand of the expression; e.g., for
a parameter change:
a = 10;
/* assume that fun changes its parameter */
b = a + fun(a);

44
CS508 Final Term Preparation | Lecture 19 to 45

Functional Side Effects


- Two possible solutions to the problem
Write the language definition to disallow functional side effects
o No two-way parameters in functions
o No non-local references in functions
o Advantage: it works!
o Disadvantage: inflexibility of two-way parameters and non-local references
- Write the language definition to demand that operand evaluation order be fixed
Disadvantage: limits some compiler optimizations
Operator Overloading
- Use of an operator for more than one purpose is called operator overloading
- Some overloaded operators are common (e.g. ‘+’ for int and float)
- Some are potential trouble (e.g. ‘*’ in C and C++)
* is also used for pointers
- Loss of compiler error detection (omission of an operand should be a detectable error)
- Some loss of readability
- Can be avoided by introduction of new symbols (e.g., Pascal’s div for integer division)
- C++ and Ada allow user-defined overloaded operators
- Potential problems
Users can define nonsense operations
Readability may suffer
Type Conversion
- Implicit Type Conversion
- Explicit Type Conversion
Implicit Type Conversions
- A narrowing conversion is one that converts an object to a type that cannot include all of the values of
the original type e.g., float to int
- A widening conversion is one in which an object is converted to a type that can include at least
approximations to all of the values of the original type e.g., int to float
- A mixed-mode expression is one that has operands of different types
- Coercion is an implicit type conversion
- Disadvantage of coercions:
They decrease in the type error detection ability of the compiler
- In most languages, all numeric types are coerced in expressions, using widening conversions
Explicit Type Conversions
- Called casting in C-based language
- Examples
C: (int) angle
Ada: Float (sum)
- Note that Ada’s syntax is similar to function calls
Errors in Expressions
- Causes
Coercions of operands in expressions
Inherent limitations of arithmetic e.g., division by zero

45
CS508 Final Term Preparation | Lecture 19 to 45

Limitations of computer arithmetic e.g. overflow or underflow


- Division by zero, overflow, and underflow are run-time errors (sometimes called exceptions)
Relational Expressions
- Use relational operators and operands of various types
- Evaluate to some boolean representation
- Operator symbols used vary somewhat among different languages (!=, /=, .NE., <>, #)
Boolean Expressions
- Operands are Boolean and the result is also a Boolean
- Operators

Boolean Expressions
One odd characteristic of C’s expressions
a<b<c
Short Circuit Evaluation
- A and B
- A or B

Lecture #44: Control Structure


• Def: A control structure is a control statement and the statements whose execution it controls
• Levels of Control Flow
1. Within expressions
2. Among program units
3. Among program statements
• Overall Design Question
What control statements should a language has, beyond selection and pretest logical loops?
Evolution
- FORTRAN I control statements were based directly on IBM 704 hardware
- Much research and argument in the1960s about the issue
- One important result: It was proven that all flowcharts can be coded with only two-way selection and
pretest logical loops
Selection Statements
Design Issues
1. What is the form and type of the control expression?
2. What is the selectable segment form (single statement, statement sequence, compound
statement)?
3. How should the meaning of nested selectors be specified?
Single-Way Selection Statement: FORTRAN, ALGOL 60 if
FORTRAN IF
- IF (boolean_expr) statement

46
CS508 Final Term Preparation | Lecture 19 to 45

Problem
- Can select only a single statement;
- To select more, a goto must be used
Two-way Selector: ALGOL 60 if,
Nested Selectors: Pascal
Multiple Selection Constructs

Lecture #45:
Actual/Formal Parameter Correspondence:
1. Positional
2. Keyword
e.g. SORT(LIST => A, LENGTH => N);
Default Parameter Values
procedure SORT(LIST : LIST_TYPE;
LENGTH : INTEGER := 100);
...
SORT(LIST => A);
Parameters and Parameter Passing
Semantic Models
- in mode, out mode, in-out mode
Conceptual Models of Transfer
1. Physically move a value
2. Move an access path
Implementation Models
1. Pass-by-value (in mode)
- Either by physical move or access path
2. Pass-by-result (out mode)
- Local’s value is passed back to the caller
- Physical move is usually used
- Disadvantages: Collision
3. Pass-by-reference (in-out mode)
i. Actual parameter collisions
e.g.
procedure sub1(a: int, b: int);
ii. Array element collisions
e.g.
sub1(a[i], a[j]); /* if i = j */
iii. Collision between formals and globals
Root cause of all of these is: The called subprogram is provided wider access to Non-
locals than is necessary
Implementing Parameter Passing
ALGOL 60 and most of its descendants use the run-time stack
- Value copied to the stack; references are indirect to the stack
- Result : same

47
CS508 Final Term Preparation | Lecture 19 to 45

- Reference : regardless of form, put the address on the stack


Design Considerations for Parameter Passing
1. Efficiency
2. One-way or two-way
- These two are in conflict with one another!
Good programming =>
limited access to variables, which means one-way whenever possible
Efficiency =>
pass by reference is fastest way to pass structures of significant size

48

You might also like