CS508 Final Term Lecture 19 To 45
CS508 Final Term 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
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
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
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
9
CS508 Final Term Preparation | Lecture 19 to 45
10
CS508 Final Term Preparation | Lecture 19 to 45
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
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
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
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
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
27
CS508 Final Term Preparation | Lecture 19 to 45
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
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
32
CS508 Final Term Preparation | Lecture 19 to 45
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
39
CS508 Final Term Preparation | Lecture 19 to 45
40
CS508 Final Term Preparation | Lecture 19 to 45
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
42
CS508 Final Term Preparation | Lecture 19 to 45
43
CS508 Final Term Preparation | Lecture 19 to 45
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
45
CS508 Final Term Preparation | Lecture 19 to 45
Boolean Expressions
One odd characteristic of C’s expressions
a<b<c
Short Circuit Evaluation
- A and B
- A or B
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
48