Upload
vinitha-sudeesh
View
239
Download
0
Embed Size (px)
Citation preview
7/31/2019 PP MANUAL Original
1/42
ProgrammingParadigmsLab Manual
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
C O N T E N T S
7/31/2019 PP MANUAL Original
2/42
SLNO. Name of program
PageNos.
Object Oriented Programming in JAVACYCLE - I
1. Program to implement Bubble Sort. 23
2. Program to implement Matrix Multiplication 24
CYCLE II
3. Program to implement the concept of Inheritance 25
4. Program to implement Runtime Polymorphism 26
5. Program to implement Arithmetic operations onComplex numbers 27
CYCLE III
6. Program to implement Binary Search Tree (BST) 28
7. Program to find Least Common Ancestor of two nodesin a Binary Tree. 32
8.Program to demonstrate synchronized concurrency -Programming for the readers and writers problem. 34
CYCLE IV
9. A Lisp program to implement Factorial of a number 36
10. A Lisp program to generate Fibonacci Series 37
11. A Lisp program to implement quick sort. 38
12. A Lisp program to implement a binary search treewith insertion, deletion and searchoperations.
39
13. A Lisp program to implement a set with membership,union and intersection operations 40
14. A Prolog program to find the G.C.D of two givennumbers. 41
7/31/2019 PP MANUAL Original
3/42
PROGRAMMING PARADIGMS LAB
Programming Languages
Programming languages are used to make machines easier to use. They
are notations to specify, organize and reason about computations. Since
programs range from prototypes that are used once and disposed to productiontools that are shared and supported a hundreds of programming languages has
been created.
Programming languages have certain features that help in two ways:
Readable and compact notations reduce likelihood of errors.
With large programs, they provide ways of organizingcomputations they can be understood one piece at a time.
Languages are divided into different levels. Machine language is native
language of a computer and is low level dependent on underlying machine.
Programming languages are designed to:
Make computing convenient for people.
Make efficient use of computing devices.
Be higher level i.e. independent of underlying machine.
General purpose i.e. can be applied to a wide range of problems.
7/31/2019 PP MANUAL Original
4/42
Machine language was used primarily as programming language.
Programs in machine language are unintelligible at the lowest level since they
consist of only 0s and 1s. So a symbolic language called assembly language a
variant of machine language in which names and symbols take place of actual
codes for machine operations, values and storage locations making individual
instructions more readable.
Random Access Machine has four main components :
A memory consisting of sequence of locations 0, 1, called
machine address each capable of holding an integer value known
as content of the location at a time.
A program consisting of a sequence of instructions.
For execution of instruction set, which has instructions for
assignment, input/output, control flow etc.
An input file consisting of sequence of values consumed one at a
time by read instruction. An output file consisting of sequence of values consumed one at a
time by write instruction.
Program execution begins from first instruction of program residing in
memory and control normally flows form one instruction to the next, except for
branch instruction such as go to i. Program stops upon execution of haltinstruction. Higher-level languages have replaced machine and assembly
language in almost all areas of programming because they provide following
benefits:
Readable notations.
Machine independence (Portability).
7/31/2019 PP MANUAL Original
5/42
Availability of program libraries.
Consistency checks during implementation that can detect errors.
Creation of new users and programs i.e. software packages.
Programming Paradigms
Introducing new language involves designing it, implementing, teaching
and supporting it. New languages introduce new programming paradigms i.e.
new ways of thinking about programming.
Four different programming paradigms that are evolved are:
Imperative Programming
Imperative languages are action oriented i.e. a computation is viewed as a
sequence of actions. Examples of imperative programming languages are
Fortran, Pascal, C etc. The evolution of imperative programming languages is
shown as tree structure below .
Fortran
Algol 160CPL*
BCPLAlgol 168
CPascal
7/31/2019 PP MANUAL Original
6/42
Imperative programming also known as structured programming and
imperative programming languages are also called structured programming
languages.
The Imperative family begins with FORTRAN; Pascal and C are general-
purpose languages i.e. they are available on a wide range of machines. Fortran
was used for scientific programming. Then came Algol60, which was very
popular to the extent that imperative family was referred to as the Algol family.
Pascal was designed as a teaching language. C was created by Dennis
Ritchie as an implementation language for software associated with the UNIX
operating system. UNIX system was rewritten in C. C provides a rich set of
operators, a terse syntax, and efficient access to the machine.
The characteristics seen in the languages of imperative family are top-down
design and stepwise refinement.
Functional Programming
Pure Functional programming is devoid of assignments and changes to
value of a variable during expression evaluation are called side effects.
Functional programs are simple due to emphasis on values, independent of an
underlying machine with its assignments and storage allocation and powerful
due to recursion and status of functions as first-class values, function can bethe value of an expression, it can be passed as an argument, and it can be put in
a data structure.
The storage management is implicit i.e. storage is allocated and
deallocated automatically.
7/31/2019 PP MANUAL Original
7/42
Basic concepts of functional language originated with LISP, a language
designed for applications in artificial intelligence (AI). The name LISP is
acronym for LISt Processing. Lisp language can be used for symbolic data
processing, symbolic calculations, electrical circuit theory, game playing,
mathematical logic etc.
Functional programming begins from LISP. Next is ISWIM, which was
only theoretical and never implemented. Then came ML, Miranda and Gofer,
which is a subset of Haskell. A sparse version of LISP is Scheme, which was
popular for research and teaching. CLOS (Common Lisp Object System) is an
object-oriented extension.
The evolution of functional programming languages is shown as tree
structure below.
Fortran
Algol60 LISP
ISWIM*
Mac Inter
Lisp Lisp
ML
SASL Scheme
7/31/2019 PP MANUAL Original
8/42
Zeta Lisp
Miranda Common Lisp
Standard ML
CLOS
Haskell
Gofer
7/31/2019 PP MANUAL Original
9/42
CS 507(P)Programming Paradigms Lab lab Manual
LISP
LISP is a functional programming language. LISP is acronym for LISt
Processing. LISP is the oldest and most widely used and was the first
functional programming language.
LISP has three types of data objects, which are atoms, lists and strings.
Atoms are basic syntactic element in LISP. Lists are specified by delimiting
their elements within parentheses. The elements in lists are restricted to atoms
as in (A B C D). Nested lists can also be specified. Lisp uses prefix notation to
specify expressions.
Storage Allocation
Internally lists are usually stored as single-linked list structures, in which
each node has two pointers and represents an element. A node for an atom has
its first pointer pointing to some representation of the atom, such as its symbol
or numeric value. A node for a sublist element has its first pointer pointing to
first node of the sublist i.e. head of the list. In both cases, the second pointer
points to the next element of the list i.e. tail of the list. A list is referenced by a
pointer to first element. The above list (A B C D) is represented as
LISP allocates memory for lists as cons cells, which has two pointers out
of which one pointing to head of the list and another pointing to tail.
Dept. of CSE 9 TEC
7/31/2019 PP MANUAL Original
10/42
CS 507(P)Programming Paradigms Lab lab Manual
Garbage Collection
Garbage collection is deallocation of cells that is no longer in use. A
standard technique for allocating and deallocating cells is to link them on a list
called a free list. The free list acts as a stack of cells; a pop operation on the
stack returns a freshly allocated cell and a push operation returns a cell back
onto the stack. In Lisp language implementation performs garbage collection
when it returns cells to free list automatically.
Three approaches for deallocation are
Lazy approach -Wait until memory runs out and only then collect
dead cells. If enough memory is available, the need for collecting
cells may never arise. The disadvantage of this approach is that all
other work comes to a halt when the garbage collector has control
of the machine.
Eager approach Each time a cell is reached, check whether the
cell will be needed after the operation; if not, deallocate the cell by
placing it on the free list. A standard technique is to set aside some
space with each cell for holding a reference count of the number of
pointers to the cell. If reference count drops to 0 cell can be
deallocated.
Another simple approach is mark-sweep approach
Mark phase- Mark all the cells that can be reached by following
pointers.
Sweep phase- Sweep through memory, looking for unmarked cells.
Unmarked cells are returned to the free list.
Dept. of CSE 10 TEC
7/31/2019 PP MANUAL Original
11/42
CS 507(P)Programming Paradigms Lab lab Manual
Logic Programming
Logic programming is the use of a formal logic notation to communicate
computational processes to a computer. Predicate calculus is the notation used
in current logic programming language.
Programming in logic programming languages do not state exactly how a
result to be computed but rather describe the form of the result. What is needed
to provide this capability for logic programming languages is a concise means
of supplying the computer with both the relevant information and an
inferencing process for computing desirable results, which is provided by
predicate calculus.
Prolog was developed for natural language processing and it uses a
specialized form of logical reasoning to answer such queries. Prolog has since
been used for a range of applications from databases to expert systems. Prolog
programs have the brevity and expressiveness of logic.
PROLOG
Prolog is a logic-programming tool.
Logic programming refers loosely to
The use of facts and rules to represent information The use of deduction to answer queries
It is based on programming with relations. A relation is a table with
n>=0 columns and a possibly infinite set of rows. A tuple in a relation is a row
in the relation. Relations are also called predicates because a relation name rel
can be thought of as a test of the form
Dept. of CSE 11 TEC
7/31/2019 PP MANUAL Original
12/42
CS 507(P)Programming Paradigms Lab lab Manual
Is a given tuple in relation rel?
Relations are specified by rules, written in pseudocode as
P if Q 1 and Q 2 and and Q k .
For k>=0. Such rules are also called Horn clauses.
A fact is a special case of a rule, in which k=0 and P holds without any
conditions, written simply as P.
Facts, rules, and queries are specified using terms for the basic syntax of
Prolog. A simple term is a number, a variable starting with an upper case letter,
or an atom standing for itself. Examples of simple terms are 0 1972 X Source
lisp algol60. A compound term consists of an atom followed by a
parenthesized sequence of subterms. The atom is called a functor and the
subterms are called arguments. In link(bcpl, c) the functor is link, and the
arguments are bcpl and c.
The consult construct reads in a file containing facts and rules, and adds
the contents at the end of the current database of rules.
Logic programming is driven by queries about relations. A query is of
the form
1, 2,.., k.
for k>=1, corresponds to the following pseudocode:
1 and 2 and.. and k.
Queries are also called goals. An instance of a term T is obtained by
substituting subterms for one or more variables of T. The same subterm must
be substituted for all occurrences of a variable. Deduction in prolog is based on
the concept of unification; the two terms unify if they have a common instance.
Dept. of CSE 12 TEC
7/31/2019 PP MANUAL Original
13/42
CS 507(P)Programming Paradigms Lab lab Manual
Languages of logic programming are called declarative languages
because programs written in them consist of declarations rather than
assignments and control of flow statements. These declarations are actually
statements, or propositions, in symbolic logic.
One of the essential characteristics of logic programming languages is
their semantics, which is called declarative semantics. The basic concept of
semantics is that there is a simple way to determine the meaning of each
statement.
Concurrency refers to potential for parallelism. The fundamental concept
of concurrent programming is the notion of a process. A process corresponds to
a sequential computation with its own computation. The thread of a sequential
computation is the sequence of program points that are reached as control flows
through the source text of the program. To achieve concurrency the processes
must interact each other in one of the two forms:
1. Communication involves exchange of data between processes.
2. Synchronization relates the thread of one process with that of another
i.e. involves exchange of control information between processes.
Examples of concurrent programming languages are Ada, Java,
Concurrent Pascal, Occuum etc.
Object-Oriented Programming
Dept. of CSE 13 TEC
7/31/2019 PP MANUAL Original
14/42
CS 507(P)Programming Paradigms Lab lab Manual
This programming paradigm originated with Simula, which was
designed as both a description language and a programming language. The key
concept of Simula was class of objects. The classification of objects into
classes and subclasses is central to object-oriented programming.
The evolution of imperative programming languages is shown as tree structure
below.
Fortran
Lisp
Algol60
CPL
ISWIM*
BCPL
Simula
ML
C Smalltalk
C++
Standard ML
C++ Standard
Dept. of CSE 14 TEC
7/31/2019 PP MANUAL Original
15/42
CS 507(P)Programming Paradigms Lab lab Manual
C++, Java and Smalltalk are popular languages for object-oriented
programming. C++ was designed to bring the benefits of objects to imperative
programming in C. C++ retains the efficiency of C. Smalltalk was designed as
a part of a personal computing environment. Java is related to C++, which is a
direct descendant of C. much of the characteristics of Java is inherited from
these two languages. From C, Java derives its syntax. Many of Javas object-
oriented features were influenced by C++.
All computer programs consist of two elements: code and data. A
program can be conceptually organized around its data. To manage increasing
complexity object oriented programming was conceived. Object oriented
program organizes a program around its data(i.e., objects) and a set of well
defined interfaces to that data. An object-oriented program can be characterized
as data controlling access to code. OOP treats data as a critical element in the
program development and does not allow it to flow freely around the system. It
ties data more closely to the functions that operate on it and protects it from
unintentional modification buy other functions, OOP allows us to decompose a
problem into a number of entities called objects and then build data and
functions around these entities. The combination of data and methods make up
a n object. The data of an object can accessed only by the methods associated
with that object. However, methods of one object can access the methods of
other objects.
Basic Concepts of OOP
Dept. of CSE 15 TEC
7/31/2019 PP MANUAL Original
16/42
CS 507(P)Programming Paradigms Lab lab Manual
Objects & Classes
Data Abstraction & Encapsulation,
Inheritance Dynamic binding
Message passing
Polymorphism
Objects and Classes: Objects are the basic runtime entities in an
OOP system. They may represent a person, a place, a bank
account, a table of data or any item that the program may handle.
When a program is executed, the objects interact by sending
messages to one another. A class is user defined data type and is a
collection of objects of similar type.
Data Abstraction and Encapsulation : The wrapping up of data
and methods into a single unit(called class) is known as
encapsulation. The insulation of data from direct access by the
program is called data hiding of information hiding.
Inheritance: - Inheritance is the process by which objects of one
class acquire the properties of objects of another class. Inheritance
supports the concept of hierarchical classification and it provides
the idea of re usability. In Java, the derived class is known as
subclass. A derived class with only one base class is called
Single Inheritance and one with several base classes is called
Multiple Inheritance. If one class is inherited by more than one
class is known as Hierarchical Inheritance. The mechanism of
deriving a class from another derived class is known as
Multilevel Inheritance. Hybrid Inheritance is a collection of
Dept. of CSE 16 TEC
7/31/2019 PP MANUAL Original
17/42
CS 507(P)Programming Paradigms Lab lab Manual
Hierachical and Multiple Inheritance. Various types of
Inheritances in graphical representation is as follows.
Dynamic Binding: Binding refers to the linking of a procedure
call to the code to be executed in response the call. Dynamic
binding means that the code associated with a given procedure call
is not known until the time of the call at run-time.
Message Passing: Objects communicate with one another bysending and receiving information. Message passing involves
specifying the name of the object, the name of the function
(message) and the information to be sent.
Polymorphism: Polymorphism is another important OOP concept.
Polymorphism means the ability to take more than one form.
Operator overloading is the process of making an operator to
Dept. of CSE 17 TEC
A
B
Single Inheritance
A B
C
Multiple Inheritance
A
DB C
HierarchicalInheritance
A
B
C
Multilevel Inheritance
A
B C
D
Hybrid Inheritance
7/31/2019 PP MANUAL Original
18/42
CS 507(P)Programming Paradigms Lab lab Manual
exhibit different behaviours in different instances. In Function
overloading a single function name can be used to handle different
number and different types of arguments. Compiler is able to select
the appropriate function for a particular call at the compile time
itself. This is known as early binding or static binding or static
linking. Compile time polymorphism means that an object is
bound to its function call at compile time. When the selection of
appropriate function is done at run time, it is termed as late binding
or dynamic binding. Thus if the appropriate member function
could be selected while the program is running, it is known as
Runtime polymorphism. Graphical representation of types of
polymorphism is as follows:
Dept. of CSE 18 TEC
Polymorphism
Compiletime
Run time
Functionoverloading
Operatoroverloading
Virtualfunctions
7/31/2019 PP MANUAL Original
19/42
CS 507(P)Programming Paradigms Lab lab Manual
Java
Java technology is both a programming language and a platform.
The Java Programming Language
The Java programming language is a high-level language that can be
characterized by all of the following buzzwords:
Simple
Architecture neutral
Object oriented
Portable Distributed
High performance
Multithreaded
Robust
Dynamic
Secure
In the Java programming language, all source code is first written in plain
text files ending with the .java extension. Those source files are then
compiled in to .class files by the Java compiler ( javac ). A .class file
does not contain code that is native to your processor; it instead contains
bytecodes -- the machine language of the Java Virtual Machine. The Java
launcher tool ( java ) then runs your application with an instance of the Java
Virtual Machine.
Because the Java Virtual Machine is available on many different
operating systems, the same .class files are capable of running on Microsoft
Windows, the Solaris TM Operating System (Solaris OS), Linux, or MacOS.
Dept. of CSE 19 TEC
7/31/2019 PP MANUAL Original
20/42
CS 507(P)Programming Paradigms Lab lab Manual
The Java Platform
A platform is the hardware or software environment in which a program
runs. We've already mentioned some of the most popular platforms like
Microsoft Windows, Linux, Solaris OS, and MacOS. Most platforms can be
described as a combination of the operating system and underlying hardware.
The Java platform differs from most other platforms in that it's a software-only
platform that runs on top of other hardware-based platforms.
The Java platform has two components:
Java Virtual Machine
Java Application Programming Interface (API)
You've already been introduced to the Java Virtual Machine. It's the base
for the Java platform and is ported onto various hardware-based platforms.
The API is a large collection of ready-made software components that
provide many useful capabilities, such as graphical user interface (GUI)
widgets. It is grouped into libraries of related classes and interfaces; these
libraries are known as packages.
As a platform-independent environment, the Java platform can be a bit
slower than native code. However, advances in compiler and virtual machine
technologies are bringing performance close to that of native code without
threatening portability.
The general-purpose, high-level Java programming language is a
powerful software platform. Every full implementation of the Java platform
gives you the following features:
Dept. of CSE 20 TEC
7/31/2019 PP MANUAL Original
21/42
CS 507(P)Programming Paradigms Lab lab Manual
Development Tools :
The development tools provide everything you'll need for compiling,
running, monitoring, debugging, and documenting your applications. As a new
developer, the main tools you'll be using are the Java compiler ( javac ), the
Java launcher ( java ), and the Java documentation tool ( javadoc ).
Application Programming Interface (API) :
The API provides the core functionality of the Java programming
language. It offers a wide array of useful classes ready for use in your own
applications. It spans everything from basic objects, to networking and security,
to XML generation and database access. The core API is very large; to get an
overview of what it contains, consult the release documentation linked to at the
bottom of this page.
Deployment Technologies : The JDK provides standard
mechanisms, such as Java Web Start and Java Plug-In, for
deploying your applications to end-users.
User Interface Toolkits : The Swing and Java 2D toolkits make it
possible to create sophisticated Graphical User Interfaces (GUIs).
Integration Libraries : Integration libraries such as IDL, JDBC,
JNDI, RMI, and RMI-IIOP, enable database access and
manipulation of remote objects.
Java technology will help you do the following:
Dept. of CSE 21 TEC
7/31/2019 PP MANUAL Original
22/42
CS 507(P)Programming Paradigms Lab lab Manual
Get started quickly : Although the Java programming language is
a powerful object-oriented language, it's easy to learn, especially
for programmers already familiar with C or C++.
Write less code : Comparisons of program metrics (class counts,
method counts, and so on) suggest that a program written in the
Java programming language can be four times smaller than the
same program in C++.
Write better code : The Java programming language encourages
good coding practices, and its garbage collection helps you to
avoid memory leaks. Its object orientation, its JavaBeans
component architecture, and its wide-ranging, easily extendible
API let you reuse other people's tested code and introduce fewer
bugs.
Develop programs more quickly : Your development time may be
as much as twice as fast versus writing the same program in C++.
Why? You write fewer lines of code and it is a simpler
programming language than C++.
Avoid platform dependencies : You can keep your program
portable by avoiding the use of libraries written in other languages.
Write once, run anywhere : Because Java applications are
compiled into machine-independent bytecodes, they run
consistently on any Java platform.
Distribute software more easily : With Java Web Start
technology, users will be able to launch your applications with a
single click of the mouse. An automatic version check at startup
Dept. of CSE 22 TEC
7/31/2019 PP MANUAL Original
23/42
CS 507(P)Programming Paradigms Lab lab Manual
ensures that users are always up to date with the latest version of
your software. If an update is available, Java Web Start will
automatically upgrade their installation.
Differences between Java and C++
Java has 2 additional data types than C++ such as Boolean and byte.
Char of java is different from char of C++ in that char of java takes 2
bytes for a character representation and it can represent all characters
from extended character set Unicode. String in java is an abstract data
type, which provides following benefits compared to string in C++ such
as reliability and portability. Main function in java is written inside class
itself whereas in C++ it is written outside.
Choice of Language
It depends partly on programming to be done and partly on external
factors such as availability, support and training. For example initial prototype
of Unix system spell checker was written by combining existing utility
programs in Unix environment. After several years an improved version of
spell checker was implemented in C to speed up checking.
Dept. of CSE 23 TEC
7/31/2019 PP MANUAL Original
24/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 1:
BUBBLE SORT
AIM : To sort N given numbers
ALGORITHM :-
Step 1: Start
Step 2: Create a class A .
a) Create a method R for reading array elements.
b) Create a method S for sorting N elements using temporary variable.
i) if (First > Second)
Temp = First
First = Second
Second = Temp
ii) Repeat the above step (N - 1) times.
c) Create a method D for displaying array.
Step 3: Create another class B.
a) Define main method.
b) Create an object of class A.
c) Call the methods R,S,D using that object.
Step 8: Stop
Dept. of CSE 24 TEC
7/31/2019 PP MANUAL Original
25/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 2:
MATRIX MULTIPLICATION
AIM : To implement Matrix Multiplication
ALGORITHM :
Step 1:- Start
Step 2:- Create a class A
a) Create a method R for reading two matrices
b) Create a method P for calculating the product of 2 matrices and
store the product in to another matrix, using equation
c[i][j]=c[i][j]+[a[i][k]*b[k][j]]
c) Create a method D for displaying the matrix
Step 3:- Create another class B
a) Define main method
b) Create an object of Class A
c) Read the row size and column size of first matrix
d) Read the row size and column size of second matrix
e) Check whether the column size of first matrix and row size of
second matrix are equal or not
f) If they are equal do matrix multiplication using the method P
mentioned in Step 2.
Otherwise display the message Matrix multiplication is not
possible.
Call the methods R, P, D using that object.
Dept. of CSE 25 TEC
7/31/2019 PP MANUAL Original
26/42
CS 507(P)Programming Paradigms Lab lab Manual
Step 4 :- Stop.
LAB 3 :
INHERITANCE
AIM :- To implement the concept of inheritance
ALGORITHM :-
Step 1:- Start
Step 2:- Create an abstract base class called shape.
a) Create 2 abstract method A & P
Step 3:-Inherit sub class-square, rectangle, circle, ellipse from base class
shape
a) Create constructor for each derived class
b) Create method A for finding area of each derived class
c) Create method P for finding perimeter of each derived class
Step 4:- Create Another class B
a) Define Main Method
b) Create Objects of each subclasses
c) Call the methods A and P with appropriate objects of the subclasses
Step 5:- Stop
Dept. of CSE 26 TEC
7/31/2019 PP MANUAL Original
27/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 4 :
RUN TIME POLYMORPHISM
AIM :- To implement Runtime polymorphism
ALGORITHM :-
Step 1:- Start
Step 2:- Create a class A
a) Create a method communicate
Step 3 :- Inherit subclasses B, C, D, E from base class A
a) Create a method, have the same name in the base class but each have
different actions
Step 4 :-Create another class B
a) Define main method
b) Create object for each subclass
c) Call the method with appropriate objects in each class
Step 5:- Stop.
Dept. of CSE 27 TEC
7/31/2019 PP MANUAL Original
28/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 5 :
COMPLEX NUMBER OPERATIONS
AIM :- To implement Complex Number Operations
ALGORITHM :-
Step 1:- Start
Step 2:- Create a class A
a) Create methods add, sub, mul and div to perform arithmetic operations
of complex numbers
b) Create method D for displaying the result.
Step 3:- Create Another class B
a) Define main method
b) Create objects of class A
c) Read 2 complex numbers
d) Call each methods add, sub, mul, and div using that object
e) Call method D using that object
Step 4:- Stop
Dept. of CSE 28 TEC
7/31/2019 PP MANUAL Original
29/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 6 :
BINARY SEARCH TREE
A binary tree is made of nodes, where each node contains a "left" part, a "right"
part, and a data element. The "root" points to the topmost node in the tree. The
left and right parts recursively point to smaller "sub trees" on either side. A null
represents a binary tree with no elements -- the empty tree. The formal
recursive definition is: a binary tree is either empty (represented by a null), or
is made of a single node, where the left and right parts (recursive definition
ahead) each point to a binary tree .
A class called Binary Tree is created which has functions those
implements the binary tree operations such as insertion, searching, preorder
traversal, postorder traversal, inorder traversal.
A class is an Abstract Data Type consisting of member data and member
functions. A class is implemented and used by instantiating it. An instance of
class is object. When an object is created it gets its own copy of variables and
share a copy of member functions. So a class acts as a template for creating
objects.
Dept. of CSE 29 TEC
7/31/2019 PP MANUAL Original
30/42
CS 507(P)Programming Paradigms Lab lab Manual
AIM :- To implement operations of BST
ALGORITHM :-
Step 1:-Start
Step 2:- Create a class A
a) Create a constructor
b) Create a method Insert for inserting elements in BST
i) Adding a node to a binary search tree involves tracing down a path of
the binary search tree, taking lefts and rights based on the comparison of
the value of the current node, and the node being inserted, until the path
reaches a dead end. At this point, the newly inserted node is plugged into
the tree at this reached dead end.
When making the comparison at the current node, the node to be inserted
travels down the left path if its value is less than the current node, and
down the right if its value is greater than the current node's value.
Therefore, the structure of the BST is relative to the order with which the
nodes are inserted.
c) Create 3 methods Preorder, Inorder, Postorder for traversing the BST
Preorder Traversal is an algorithm , which visits each node of a tree
first, and then its left subtree and its right subtree. The following is the
procedure to print all the elements of a binary search tree in preorder:
Preorder (x)
if x != NIL: {
write (key[x]);
preorder (left[x]);
preorder (right[x]); }
Dept. of CSE 30 TEC
7/31/2019 PP MANUAL Original
31/42
CS 507(P)Programming Paradigms Lab lab Manual
Inorder Traversal is an algorithm , which visits each node of a tree
after its left subtree and before its right subtree. Therefore, inorder
traversal shows the values stored in a binary search tree in order. The
following is the procedure to print all the elements of a binary search tree
in order:
Inorder (x)
if x != NIL: {
inorder (left[x]);
write (key[x]);
inorder (right[x]); }
The inorder procedure is called recursively twice for each element (once
for the left child and once for its right child), and the element is visited
right between them. Therefore, the construction time is equal to (n).
Postorder Traversal is an algorithm , which visits each node of a tree
after its left subtree and its right subtree. The following is the procedure
to print all the elements of a binary search tree in post order:
Postorder (x)
if x != NIL: {
postorder (left[x]);
postorder (right[x]);
write (key[x]);
}
a) Create another method Search for searching the BST
Dept. of CSE 31 TEC
7/31/2019 PP MANUAL Original
32/42
CS 507(P)Programming Paradigms Lab lab Manual
To enter the value to be searched and search function is performed by
passing the search value as parameter.The following is the pseudocode to
search for the element k in a binary search tree whose root is x:
Search (x, k)
while x != NIL and k != key[x]
if k < key[x] then x = left[x]
if k > key[x] then x = right[x]
return x
If k is not an element of the binary search tree x, the function returns
NIL; otherwise, it returns the the node with the key value equal to k.
b) Create a method D for Displaying elements in BST
Step 3:- Create Another Class BST
a) Define main method
b) Create an object of the class A.
c) Call the appropriate methods using that object
Step 4:- Stop
Dept. of CSE 32 TEC
7/31/2019 PP MANUAL Original
33/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 7 :
LEAST COMMON ANCESTOR OF TWO NODES IN A TREE
AIM :- To find the least common ancestor of two nodes in a tree
ALGORITHM :-
Step 1:- Start
Step 2:- Create a class A
a) Define main method
b) Read the nodes in a tree.
c) Read the nodes, whose L C A is to be found
d) Create an array tree[] is used to store each nodes of a tree in level
order.
e) Create another array nodes[] is used to store the 2 nodes, whose
LCA to be found.
f) Find the position of the nodes (whose L C A to be found) in the
array by checking
If (node[0] = = tree[i]) then p=i
If (node[1] = = tree[i]) then q=i
g) using these positions find the parent of each node by checking
if(p=q) then m=n=p, otherwise
if(pq) then m=q, n=p.
h) if both nodes parent are same ,then the corresponding node is the
L C A , otherwise we continue till the position reaches zero.
i) find the L C A by do the following steps
j) While (m!=n && m0 && n 0) do the following steps
1) while(m
7/31/2019 PP MANUAL Original
34/42
CS 507(P)Programming Paradigms Lab lab Manual
b) n = (n-1) / 2
2) while (m>n) do the steps a & b.
a) if (m%2 = = 0) then m=(m-2)/2 otherwise
b) m=(m-1)/2
g) if (m= =n) then display L C A is tree[m]
Step 3: - Stop.
Dept. of CSE 34 TEC
7/31/2019 PP MANUAL Original
35/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 8:
CONCURRENCY - READERS WRITERS PROBLEM
AIM : To demonstrate synchronized concurrency - Programming for the
readers and writers problem.
ALGORITHM:-
Step 1: Start.
Step 2: Define a class writer that inherits from thread class with data memebr
choice and num.
Step 3: Define method write that acts the constructor for the writer class.
Step 4: Set choice = h, define method run & j=0
Step 5: Repeat the following steps 10 times
Step 6: Call function choice put val(j)
Step 7: Print value j.
Step 8: call function sleep with arguement 1000
Step 9: Increment the value of j by 1.
Define a class reader that inherit threaded class with data members choice &
integer val &j
Step 1: Define a method reader that act as the constructor with parameter h
Step 2: Set choice = h, define method run & j=0
Step 3: Repeat the following steps 10 times
Step 4: Set val = choice get val ()
Step 5: Print value val.
Step 6: call method sleep.
Step 7: Increment the value of j by 1.
Define a class writereadhole with private data members available and value.
Step 1: Define a synchronised method getval that returns an integer.
Dept. of CSE 35 TEC
7/31/2019 PP MANUAL Original
36/42
CS 507(P)Programming Paradigms Lab lab Manual
Step 2: If available = false call method wait else go to step 4.
Step 3: Set available = false and call method notifyall().
Step 4: Return value
Step 5: Define a synchronised method putval with parameter val.
Step 6: If available = true call method wait else go to step 4.
Step 7: Set value val & available = true and call method notifyall().
Define a class rw that contain the main method
Step 1: Create an object hole of type writereadhole.
Step 2: Create an object u and v of type write & reader respectively.
Step 3: Initialise threads by calling v.start() & u.start().
Step 4: Stop.
Dept. of CSE 36 TEC
7/31/2019 PP MANUAL Original
37/42
CS 507(P)Programming Paradigms Lab lab Manual
LISP PROGRAMS
LAB 9 :
FACTORIAL OF A NUMBER
AIM : To find factorial of a number
ALGORITHM :
Step 1:- Start
Step 2:- Define the function fact(n)
a) if(n=0) then return 1
b) Otherwise recursively call the function fact(n-1) and multiply
with n
Step 3:- Define another function main
Step 4:- Read the number n
Step 5:- Call the function fact(n)
Step 6:- Stop
Dept. of CSE 37 TEC
7/31/2019 PP MANUAL Original
38/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 10:
FIBONACCI SERIES
AIM : To get n Fibanocci numbers.
ALGORITHM :
Step 1:- Start
Step 2:- Define function fib()
Step 3:- Read the limit n
Step 4:- Assign fib1 0 , fib2 1
Step 5:-Do the steps 6,7,8,9 n times
Step 6:- Display fib2
Step 7:- temp fib2
Step 8:-fib2 fib1+fib2
Step 9:-fib1 temp
Step 10:-Stop
Dept. of CSE 38 TEC
7/31/2019 PP MANUAL Original
39/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 11 :
QUICK SORT
AIM : To implement quick sort on a list of numbers .
ALGORITHM :
Step 1: Start
Step 2: Declare a function.Quick sort which receives three arguements
arr,low & high in which arr is a list of numbers & does the following
Step 3: If high > low then initialize i =0 then j = high +1
Initialize index = low & pivot = element of arr at positionindex.
Step 4: Repeat the following steps.
Step 5: Repeat incrementing i until i become greater than high or pivot
become less than element of arr at i.
Step 6: Repeat decrementing j until j become less than or equal to low or
Pivot become greater than or equal to element of arr at j.
Step 7: If i > j then exit from loop.
Step 8: Interchange the elements of arr at j and low.
Step 9: Call the function quicksortwithh arr, i and high
Step 10: Return arr.
Step 11: Declare a function qsort which receive one parameter sequence
which is a list of elements.
Step 12: Call the function quicksort with arguements sequence, 0 and length
of sequence -1
Step 13: Stop
Dept. of CSE 39 TEC
7/31/2019 PP MANUAL Original
40/42
CS 507(P)Programming Paradigms Lab lab Manual
LAB 12 :
BINARY SEARCH TREE
AIM : To create binary tree to perform insert & search operations.
ALGORITHM :
Step 1: Start
Step 2: Define root.
Step 3: Defien function empty tree=nil
Step 4: Define the functions right-subtree and left-subtree to create rght
subtree and left subtree
Step 5: Define the function insert
If root = nul, create root with left anf right subtrees are nil.
If root> number, create left subtree
If root< number, create right subtree, else no operation
Stept 6: Define the function search
If root = null, print number not found
Elseif If root = number , print number found
Else
If root< num call function Search(right-subtree)
Else call the function Search(left-subtree)
Step7: Stop.
Dept. of CSE 40 TEC
7/31/2019 PP MANUAL Original
41/42
7/31/2019 PP MANUAL Original
42/42
CS 507(P)Programming Paradigms Lab lab Manual
PROLOG PROGRAM
LAB 14:
GCD OF TWO GIVEN INTEGERS
AIM : To find the GCD of two given numbers.
ALGORITHM: -
1. if(i!=j)
2. if(i>j)
3. i=i-j
4. if(j