0% found this document useful (0 votes)
11 views

DBMS & Data Structure_BCA

The document outlines the curriculum for a Database Management System (DBMS) course in the Bachelor of Computer Applications (BCA) program, covering key topics such as data concepts, relational database models, SQL, PL/SQL, and data models. It discusses the advantages and disadvantages of both file-based systems and DBMS, emphasizing the importance of data integrity, security, and management. Additionally, it provides insights into various data models, including hierarchical and relational models, along with examples and explanations of their structures.

Uploaded by

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

DBMS & Data Structure_BCA

The document outlines the curriculum for a Database Management System (DBMS) course in the Bachelor of Computer Applications (BCA) program, covering key topics such as data concepts, relational database models, SQL, PL/SQL, and data models. It discusses the advantages and disadvantages of both file-based systems and DBMS, emphasizing the importance of data integrity, security, and management. Additionally, it provides insights into various data models, including hierarchical and relational models, along with examples and explanations of their structures.

Uploaded by

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

DATABASE MANAGEMENT SYSTEM

BACHELOR OF COMPUTER APPLICATIONS (BCA)


SEMESTER-II
Zenex Vision Degree College DBMS –BCA- SEM-II

BACHELOR OF COMPUTER APPLICATIONS (BCA)


SEMESTER-II
DATABASE MANAGEMENT SYSTEM

UNIT-1

Introduction to Database Management System: Introduction to Data, Information, Database, Database


Management Systems, file-based system, Drawbacks of file-based system, Classification of Database Management
Systems, advantages and disadvantages of database approach, services of database systems, Components of
Database Management System.

UNIT-2

The Relational Database Model: Various Data Models, Relational Database Model, Keys used in Relational
model, Relational Data Integrity, Relational set operators, Relationships within the Relational Database,
Codd‟s relational database rules.

Entity-Relationship Model: Introduction, The components of an Entity Relationship model, entities, attributes
relationships, Classification of Entity sets, Attribute Classification, Relationship Degree, and Relationship
Classification.

UNIT-3

Introduction to SQL: Structured Query Language (SQL)-Introduction-SQL data types-SQL Literals, SQL
operators: Arithmetic Operators- Comparison Operators-Logical Operators- Set Operator Precedence.
Types of SQL Commands: DDL, DML, TCL, DCL
Tables: Creating tables – Altering tables – dropping tables – displaying structure of table – Inserting, updating,
and deleting: INSERT statement-bulk inserts of data – UPDATE statement – DELETE statement

UNIT-4

Queries and Sub queries: using SELECT statement


Aggregate Functions: Introduction – COUNT (), COUNT (*), SUM (), AVG (), MAX (), and MIN () functions.
Multiple table processing: Joins and Unions
TCL Commands: COMMIT, ROLLBACK, and SAVEPOINT statements
DCL Commands: Privileges and roles – Granting and Revoking privileges and roles- GRANT and REVOKE
statement

UNIT-5

PL/SQL: Introduction, Structure of PL/SQL program, PL/SQL Data Types, operators used in PL/SQL, variables,
declaring variables in PL/SQL, Creating and running a PL/SQL Program, Control structures: Conditional Control
statements, Iterative Control statements, Cursors: types of cursors, Steps to create a cursor, are using cursors in
PL/SQL program.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

2
Zenex Vision Degree College DBMS –BCA- SEM-II

UNIT-1

1. What is Data, Information , Database, and Database Management System? Explain in detail.

DATA: The collection of “raw facts" is called data. It does not provide any specific meaning. The data may be
numeric, text, audio, video etc.,

Ex: is, girl, a, swetha, good etc., are the data.

Ex 2: 16 Ravi 9000
29 Balu 8000 raw facts (data)
13 Suresh 8000

INFORMATION: The collection of processed data is called as information. The information has a specific
meaning. The information can be in a table format or graphical format.

Timely information is the key to good decision making. Timely and useful information requires accurate data.

Ex 1: Swetha is a good girl.

Ex 2: SNo SName Fee


16 Ravi 9000
29 Balu 12000 This is the information of a student.
13 Suresh 8000

Hence, such data must be generated properly, and it must be stored in a format that is easy to access and process.
Data management is a procedure that focuses on the proper generation, storage, and retrieval of data. So various
database management systems are developed to help data management.

DATABASE:

Database is a collection of related data and data is a collection of facts and figures that can be processed to
produce information.

A Database is the collection of logically interrelated data about a particular organization. It is a shared, integrated
computer structure that store end user data and metadata. A database is developed to quickly retrieve needed data.
For example, Employee database, publisher database, student database, Bank database, hospital database, library
database and so on.

3
Zenex Vision Degree College DBMS –BCA- SEM-II

for example: A student database is shown as

SNo Student Name Fee


16 Ravi 9000
29 Balu 12000
13 Sai 8000
24 Sujith 9000

A Database is a shared, integrated computer structure that stores a collection of END USER DATA and META
DATA.

End user data is the raw facts defined by the user.

Meta data:-Meta data means data about data (or) the data that describes the properties (or) characteristics of other
data is called "meta data". In which the end user data is integrated and managed.

The meta data provides a description of the data characteristics like data type, field size , allowable values and
descriptions. for example, the meta data for a student database is

Column Data type width min max description


name
Sno Number 5 0 ------- Student no
Sname Varchar2 20 ---------- -------- Student name
fee number 8,2 5000 50000 --------

File-based System

2. What is a File?

FILE:

A file is a collection of bytes. All data is stored as a file with a file name within the disk. It stores data in the form
of records. A record is a collection of fields. The structure of a file is known to the software that manipulates it.

3. What is a File System or File-Based System? Advantages and drawbacks of file-based system?

FILE SYSTEM:

In early processing systems, an organization‟s information was stored as groups of records in separate files. These
file processing systems consist of few data files and many application programs. Programmers using programming
languages such as COBOL, C, and C++ to write applications to access files to perform data management.

As systems became more complex, file processing system had little flexibility and difficult to maintain.

4
Zenex Vision Degree College DBMS –BCA- SEM-II

Basic File Terminology:

Data: data are raw facts. The data can be a single character, such as an alphabet, digit or symbol. A single
character requires 1 byte of computer storage.

Field: A character or group of characters (alphabetic or numeric) that has a specific meaning. A field is used to
define and store data is also called column.

Record: A set of one or more fields that describes a person, place, or thing, for example, the fields that represent
record for a student consists of name, address, phone number, date of birth, etc is also called row.

File: A collection of related records is called a file. For example, a file may contain data about students of college
etc.

ADVANTAGES:

1. Easy to use
2. The data files can be easily located in memory devices.
3. Inexpensive
4. They occupy less space in memory devices.
5. Faster performance
6. Suitable for personal data management
7. They can be opened in any editor like any other text files.

DISADVANTAGES (or) DRAWBACKS (PROBLEMS WITH FILE SYSTEMS)

1. Program-data dependency: in file oriented approach each and every program maintains the file
descriptions. If any changes made to the file structure then it requires changes in all programs. Sothe
programs and data are dependent to each other.
2. Data redundancy and inconsistency: In file systems, the same information may be duplicated inseveral
files. So the repetition of data increases memory wastage and inconsistency in the data.
3. Difficulty in accessing data: It is difficult to easily retrieve required data in file processing systems.
They require programs to access needed data.
4. Recovery problem: When a failure occurs in file processing system, it is difficult to restore the data to
the consistent state that existed prior to the failure. It doesn‟t provide backup and recovery of data if
it is lost.
5. Lengthy development: File oriented approach takes more time to develop the application programs.
Each and every change of a file requires changes in all application programs.
6. Integrity problems: In file oriented systems, it is difficult to maintain integrity constraints. Hence
invalid data can be entered into the data files.
7. Sharing problems: In file oriented systems, it is difficult to share the data among several users. It
requires programs for sharing of data.
8. Security problems: In file processing systems, there is no centralized system to control the data. Soit is
not possible to provide better securities to the data files.
9. Limited capacity: Only one user can access data at a time.
10. Limited functionality: There is no efficient query processing in the file system.
Note: These file systems are used to handle a single or multiple files and are not very efficient.

5
Zenex Vision Degree College DBMS –BCA- SEM-II

DATABASE MANAGEMENT SYSTEM

4. What is DBMS? Explain advantages and disadvantages.

A database management system stores data in such a way that it becomes easier to retrieve, manipulate, and
produce information. (or)

A database management system (DBMS) refers to the technology for creating and managing databases. DBMS is
a software tool to organize (create, retrieve, update, and manage) data in a database. (or)

Database Management System (DBMS) is software for storing and retrieving users‟ data while considering
appropriate security measures. It consists of a group of programs which manipulate the database. The DBMS
accepts the request for data from an application and instructs the operating system to provide the specific data.

Some popular of DBMS are:

 MySQL
 Microsoft Access
 Oracle
 Dbase
 PostgreSQL
 FoxPro
 IBM DB2
 LibreOffice Base
 Microsoft SQL Server
 MariaDB etc.
ADVANTAGES:

 Redundancy problem can be solved: In the File System, duplicate data is created in many places because
all the programs have their own files which created data redundancy resulting in wastage of memory. In
database system, all the files are integrated in a single database. So there is no chance of duplicate data.
The data descriptions are stored in a central location called ”Data Dictionary”. The application programs
are stored separately in a database system. The changes in the data do not require changes in the programs.
Hence the program and data are independent to each other.
 Has a very high security level: Data security level is high by protecting your precious data from
unauthorized access. Only authorized users should have the grant to access the database with the help of
credentials.
 Avoidance of inconsistency: Data consistency is nothing but if you want to update data in any files then
all the files should not be updated again. In DBMS, data is stored in a single database so data becomes
more consistent in comparison to file processing systems . The database system does not allow the repeated
data into the database. The reduction of duplicated data minimizes memory wastage. Hence consistent data
can also be maintained in the database.
 Presence of Data integrity: Data integrity makes unification of so many files into a single file. DBMS
allows data integrity which makes it easy to decrease data duplicity Data integration and reduces
redundancy as well as data inconsistency.
 Support multiple users: DBMS allows multiple users to access the same database at a time without any
conflicts.
 Shared data: Data can be shared between authorized users of the database in DBMS. All the users have
their own right to access the database. Admin has complete access to the database. He has a right to assign
users to access the database.
 Any unauthorized access is restricted: Unauthorized persons are not allowed to access the database
because of security credentials.

6
Zenex Vision Degree College DBMS –BCA- SEM-II

 Enforcement of standards: As DBMS have central control of the database. So, a DBA can ensure that all
the applications follow some standards such as format of data, document standards etc. These standards
help in data migrations or in interchanging the data.
 Provide backup of data: Data loss is a big problem for all the organizations. In the file system users
have to back up the files in regular intervals which lead to waste of time and resources. DBMS solves this
problem of taking backup automatically and recovery of the database.

DISADVANTAGES:
1. High Cost
The high cost of software and hardware is the main disadvantage of the database management system.
Database users require a high-speed processor and huge memory size to use the database on the DBMS.
Sometimes, users require costly machines for maintaining databases.
Organizations need a trained and highly paid technical database administrator for using and maintaining the large
database systems.
2. Huge Size
The size of the database is not big at the initial state, but when the user stores a large amount of data, then it creates
many problems. Due to the huge data, database systems do not provide good results and do not run efficiently.
That's why the size is another limitation of the database systems.
3. Database Failure
In the database systems, all the data or information of an organization is stored in one centralized database. If the
database of that organization fails, then the data is lost, and the organization will collapse. So, database failure is a
big problem with the database management system.
4. Complexity
Database management system (DBMS) is so complex for non-technical users. So, it isn't easy to manage and
maintain database systems. Therefore, training for the designers, users, and administrators is necessary to
efficiently run the database systems.
5. Increased Staff Cost
DBMS requires an educated and skilled staff for managing and maintaining the databases. So, we need to spend a
lot of money to get this level of trained and experienced staff.
6. Requirement of Technical Staff
A non-technical people can't understand the complexity of the database. So, the technical staff is required for
maintaining and handling the database management system.
7. Cost of Data Conversion
It is one of the big disadvantages of the database management system because the cost of data conversion is very
high. There is a requirement for trained, skilled, and experienced database administrators for converting the data
smoothly.
8. Performance
Performance is another big disadvantage of database systems because the speed of the database systems for small
firms and organizations is very slow. Hence, the performance of the database systems in small organizations is
poor.

7
Zenex Vision Degree College DBMS –BCA- SEM-II

CLASSIFICATION OF DATA MODELS

5. Explain Data Models in DBMS with examples.

A database model describes the database structure of DBMS. The structure of database refers to the data types,
constraints and relationships used on the data.

The data model also describes the basic operations of retrieving the data from a database and updating the data in
the database. There are mainly four data models. They are…

1. Hierarchical Data Model


2. Relational Data Model
3. Network Data Model
4. Object-Oriented Data Model

Hierarchical Data Model:

Hierarchical Database System Structure was developed by IBM in the early 1960s.
In hierarchical data model, data is organized in a tree-line structure. The tree structure consists of hierarchy of
parent and child data segments.
This type of database management software allows one-to-one and one-to-many relationships, i.e., a parent node
can have one or multiple child nodes, whereas the children node can only have one parent node.

It is simple but inflexible due to the parent-child one-to-many relationship. They are mostly used in Banking and
Telecommunications industries to build high performance and manage applications.

Eg: IBM Information Management System (IMS).

Relational Data Model:

The relational model was introduced by Dr. E. F. Codd. It is a conceptual theory of data that is based on the
mathematical theory of relations.

In a relational model, the data is stored in tables. There are three main terms used frequently in relational database
models. They are relations, attributes, and domains. A relation is a table with columns and rows. The name
columns of the relation are called attributes, and the domain in the set of values of the attributes.

The properties of a relation (table) in a relational model are as follows. Each row can contain a single value for
each of its attributes. Same field

BookId BookTitle AuthorId Publisher Price AuthorId Name


B0001 Java A0001 Himalaya 1560 A0001 Herbert Schildt
B0002 C++ A0004 McGraw Hill 730 A0002 Balaguruswamy
B0003 DBMS A0005 Pearson 530 A0003 Dr. N. Nageswar
B0004 MS Office A0002 dreamtech 450 Rao
A0004 Kathy Sierra

8
Zenex Vision Degree College DBMS –BCA- SEM-II

Relational database depicts the relation between two or more tables.


Eg: Oracle, SQL Server, MySQL, SQLite, and IBM DB2.
Store

Network Data Model: Customer Manager Salesman

Charles Bachman developed the first DBMS at


Honeywell called Integrated Data Store (IDS).

Order Items

The network model is also called CODASYL (Conference On Data Systems Language) model. It recognizes data
using set constructs. Each set consists of an owner (parent) record type and a member (child) record type.
In this model, a record may be an owner in any number of sets, and a member in any number of sets. So this model
has ability to handle many-to-many (N:N) relationships. Thus it allows a record more than one parent.

Eg: some famous network databases are

TurboIMAGE, Integrated Database Management System (IDMS), Integrated Data Store (IDS)

Object-Oriented Data Model:

Object oriented data model is based upon real world situations. These situations are represented as objects, with
different attributes. All these objects have multiple relationships between them.

The object-oriented model consists of a collection of objects. It supports OOP concepts like objects, classes,
inheritance, polymorphism etc. in the query language.

An object-oriented data model allows us to store different types of data. It is suited for multimedia applications as
well as with complex relationships. It allows fully integrated databases that hold data such as text, pictures, audio
and video. SHAPE
getArea() getPerimeter()
Eg:

CIRCLE RECTANGLE TRIANGLE


Center Radius Length Breadth Base Height

Shape, Circle, Rectangle and Triangle are all objects in this model.
Circle has the attributes Center and Radius, Rectangle has the attributes Length and Breadth, and Triangle has the
attributes Base and Height.

9
Zenex Vision Degree College DBMS –BCA- SEM-II

TYPES OF DATABASES

6. Explain types of databases.

A database is a shared, integrated computer structure that stores a collection of end user and metadata. A DBMS
can support different types of databases. The databases can be classified as follows.

DATABASES

Based on Users Based on Location Based on usage

Single User Multi User Centralized Distributed Operational Dataware House

Based on Users

a). Single User Database: A single use database support only one user at a time. A single user database that runs on
a personal computer is called personal or desktop database. There is no sharing of data in single user database.

b). Multi User Database: A multi user database support multi users at the same time. When the multiuser database
Databa
supports few users (less than 50) then it is called workgroup database. When the database supportssemany users
User
(more than 50) then it is called enterprise database. System

User 1 Databa
User User
se
System

Based on Location:
User
a). Centralized Database: A database that supports data located at a single site (location) is called a centralized
database. This location is most often a central computer or database system that can be a desktop or server CPU, or
a mainframe computer.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

b). Distributed Database: A distributed database is a database in which data is stored across different physical
locations. It may be stored in multiple computers located in the same physical location.

A distributed database is a database that consists of two or more files located in different sites either on the same
network or on entirely different networks. Portions of the database are stored in multiple physical locations and
processing in distributed among multiple databases nodes.

Based on Data Usage:

Operational Database: A database that is designed to support a company‟s day-to-day operations is called an operation

Data warehouse: A data warehouse is a large storage space. It collects data from various sources on locations. The data wa
7. What are the functions and services of DBMS?

Functions and services of DBMS

A DBMS performs several important functions that guarantee integrity and consistency of data in the database. Most of the
i) Data Storage Management: It provides a mechanism for management of permanent storage of the data. The internal sch

manager interfaces with the operating system to access the physical storage.

(ii) Data Manipulation Management: A DBMS furnishes users with the ability to retrieve, update and delete
existing data in the database.

(iii) Data Definition Services: The DBMS accepts the data definitions such as external schema, the conceptual
schema, the internal schema, and all the associated mappings in source form.

(iv) Data Dictionary/System Catalog Management: The DBMS provides a data dictionary or system catalog
function in which descriptions of data items are stored and which is accessible to users.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

(v) Database Communication Interfaces: The end-user's requests for database access are transmitted to DBMS in
the form of communication messages.

(vi) Authorization / Security Management: The DBMS protects the database against unauthorized access, either
international or accidental. It furnishes mechanism to ensure that only authorized users an access the database.

(vii) Backup and Recovery Management: The DBMS provides mechanisms for backing up data periodically and
recovering from different types of failures. This prevents the loss of data,

(viii) Concurrency Control Service: Since DBMSs support sharing of data among multiple users, they must
provide a mechanism for managing concurrent access to the database. DBMSs ensure that the database kept in
consistent state and that integrity of the data is preserved.

(ix) Transaction Management: A transaction is a series of database operations, carried out by a single user or
application program, which accesses or changes the contents of the database. Therefore, a DBMS must provide a
mechanism to ensure either that all the updates corresponding to a given transaction is made or that none of them is
made.

(x) Database Access and Application Programming Interfaces: All DBMS provide interface to enable
applications to use DBMS services. They provide data access via Structured Query Language (SQL). The DBMS
query language contains two components: (a) a Data Definition Language (DDL) and (b) a Data Manipulation
Language (DML).

THE DATABASE SYSTEM ENVIRONMENT OR COMPONENTS OF A DATABASE SYSTEM

7. What are the components of database or database environment? Explain in detail.

A database management system (DBMS) consists of several components. Each component plays very important
role in the database management system environment. The major components of database management system are:

1. Hardware
2. Software
3. People
4. Procedures
5. Data

1. Hardware (H/W):-It refers to all of the system's physical devices like micro computers ,main frames ,work
stations, storage devices , printers, I/O channels, network devices etc., It is impossible to implement the DBMS
without the hardware devices. In a network, a powerful computer with high data processing speed and a storage
device with large storage capacity is required as database server.

2. Software (S/W):-To make the database system function fully ,3 types of software are required for a database
system. They are:-
a. operating system s/w
b. DBMS s/w
c. application programs and utility s/w

1
Zenex Vision Degree College DBMS –BCA- SEM-II

Operating System S/W:-It manages all hardware components and makes it possible for all other software to run
on the computers. Examples of operating system s/w are Microsoft windows, UNIX, LINUX etc.,

DBMS S/W:-It manages the database within the database system. Examples of DBMS s/w are Microsoft access
and SQL Server, Oracle, IBM's DB2 etc.,

Application Programs and Utility S/W:-These are used to access and manipulate data in the DBMS and to
manage the computer environment in which data access and manipulation take place.

(or)

Application programs developed in programming languages such as C++, Visual Basic that are used to to access
database in database management system. Each program contains statements that request the DBMS to perform
operation on database. The operations may include retrieving, updating, deleting data etc . The application program
may be conventional or online workstations or terminals.

Utilities are the s/w tools used to help manage the database system's computer components.

3. People:- The users are the people who manage the databases and perform different operations on the databases
in the database system. Based on their job, the users are classified into 5 types. They are:-

i. System administrators

ii. Database administrators

iii. Database designers

iv. System analysts and programmers

v. End users

i. SYSTEM ADMINISTRATORS: They are the persons who supervise the database system's generaloperations.

ii. DATABASE ADMINISTRATORS: A person who is responsible for managing the overall database
management system is called database administrator or simply DBA.

iii. DATABASE DESIGNERS: Database designers are the persons, who can design the database structure. For
success of an organization, a good database design is most important.

Iv.SYSTEM ANALYSTS AND PROGRAMMERS: Application programmers:-System analysts and


programmers are the persons, who can design and implement the application programs. They design and
create the data entry screens, reports and procedures through which end users access and manipulate database's
data. That means The people who write application programs in programming languages (such as Visual Basic,
Java, or C++) to interact with databases are called Application Programmers.

v. END USERS: The end-users are the people who interact with database management system to perform
different operations on database such as retrieving, updating, inserting, deleting data etc.

4. PROCEDURES: Procedures refer to the instructions and rules that help to design the database and to use the
DBMS/database system. The users that operate and manage the DBMS require documented procedures on hot use
or run the database management system. These may include.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

1. Procedure to install the new DBMS.


2. To log on to the DBMS.
3. To use the DBMS or application program.
4. To make backup copies of database.
5. To change the structure of database.
6. To generate the reports of data retrieved from database.

5. DATA: Data is the most important component of the DBMS. The main purpose of DBMS is to process the data.
The processed data is called information. In DBMS, databases are defined, constructed and then data is stored,
updated and retrieved to and from the databases. The database contains both the actual (or operational) data and the
metadata (data about data or description about data). What data should be stored in a database and how the data is
to be organized in a database is a database designer's job.

A database environment is a collective system of components that comprise and regulates the group of data,
management, and use of data, which consist of software, hardware, people, techniques of handling database, and
the data also.

Here, the hardware in a database environment means the computers and computer peripherals that are being used
to manage a database, and the software means the whole thing right from the operating system (OS) to the
application programs that include database management software like M.S. Access or SQL Server. Again the
people in a database environment include those people who administrate and use the system. The techniques are
the rules, concepts, and instructions given to both the people and the software along with the data with the group of
facts and information positioned within the database environment.

The graphical representation of database system environment is shown as:

1
Zenex Vision Degree College DBMS –BCA- SEM-II

UNIT-2

THE RELATIONAL DATABASE MODEL

INTRODUCTION: The relational data model was developed in 1970 by prof .E. F. Codd. This data model
organizes the data in the form of tables. The tables are also called as relations. The relational data model consists of
mainly 3 components. They are:

1. Data structure
2. Data manipulation
3. Data integrity

I.DATA STRUCTURE: It defines organization of data in the form of tables containing rows & columns.

2. DATA MANIPULATION: It performs various operations like insert, delete, update, and so on in the database.

3. DATA INTEGRITY: It provides facilities to specify rules that maintain the integrity of data when they
are manipulated.

A LOGICAL VIEW OF DATA:

The relational models enable you to view the data logically rather than physically. The logical view of the
relational database is facilitated by the creation of data relationships based on the logical construct called as a
"table".

A table is a two dimensional structure contains rows & columns. In these rows & columns, the data is stored.

For ex: student table shown as

Regdno Sname htno fee


16 ravi 34 9000
29 balu 67 12000
13 sai 89 8000
24 sujith 30 9000

Properties (or) Characteristics of a relation (or) Table:


A relation is a table. But all the tables are not relations. Because the relations have several properties. They are:
1. A table is perceived as a two dimensional structured composed of rows & columns.
2. Each attribute (or) column within a table has a unique name.
3. An entry at the intersection of each row & column should be single value.
4. Each row in a table should be unique.
5. Each table must have an attribute (or) a combination of attributes that uniquely identifies each row.
That means each table have a primary key.
6. All values in a column must conform to the same data type.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

KEYS USED IN RELATIONAL MODEL

Key is an attribute (also known as column or field) or a combination of attributes that is used to identify
records. They are also called Identifier Attributes.
1. Super Key: A super key is one or more attributes that identify the records uniquely. Any Unique key
with N Unique key combination is called a super key of the relationship. A table can have many Super
Keys.
Example: Consider relation
A table can have many Super Keys.
the relation, Student (HTNO, Stname, Course, Address)
The super keys are
i. HTNO}
ii. {HTNO, Stname}
iii. {HTNO, Stname, Course} iv. {HTNO, Stname, Course, Address

1. Super Key: A super key is one or more attributes that identify the records uniquely. Any Unique key will
Unique key combination is called a super key of the relationship. A table can have many Super Keys. Example:
Consider the relation,
Student (HTNO, Stname, Course, Address)
The super keys are
i. {HTNOY
ii. ii. {HTNO, Stname}
iii. iii. {HTNO, Stname, Course}
iv. iv. {HTNO, Stname, Course, Address }
2. Candidate Key:
A candidate key can be defined as minimal Super Key. It is a set of one or more attributes that unique identify a
record in a relation.
For example, consider the relation
Student (HTNO, Stname, Course, Address) The super keys are
i. {HTNO} → It is Candidate Key. Because it contains minimal (only one) attributes. Isi.{HTNO, Stname}
iii. {HTNO, Stname, Course},
iv. {HTNO, Stname, Course, Address
3. Primary key: The primary key is one or more attributes that identify a row uniquely in a table. Any
candidate key is a primary key of a table. It is chosen by database designer while creating a table.
Example: {HTNO}
4. Foreign key:- A foreign key is an attribute in a table holds the values of an attribute of another or same table.
It present in child table.
For example,
Student(HTNO, Stname, Course, Address) Heře
HTNO is the Primary Key Marks (HTNO, Sub1, Sub2) Here, HTNO is the Foreign Key.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

RELATIONAL DATA INTEGRITY


DATA INTEGRITY CONSTRAINTS

Relational database integrity rules are very important to good database design .Many RDBM'S enforce integrity
rules automatically.

An integrity constraint is a condition used to prevent invalid data entity into the table. It enforces rules of the
columns in a table. Constraints are use d to maintain relational data integrity. A constraint can be specified while
creating or altering table structure.

Syntax to define constraints:

CREATE TABLE tablename (column datatype(size) columnconstraint, …., tableconstraints);

The columnconstraint and tableconstraints can be any type of data integrity constraints.

Types of Constraints:

There are three types of constraints in SQL to maintain integrity while inserting or updating data of a table

1. Domain Integrity Constraints (NOT NULL, CHECK)


2. Entity Integrity Constraints (UNIQUE, PRIMARY KEY)
3. Referential Integrity Constraints (FOREIGN KEY ... REFERENCES)

1. Domain Integrity Constraints: Domain constraints allow only specified values into a column, NOT NULL
and CHECK constraints are the domain constraints.

a). NOT NULL: It doesn‟t allow null values. It must be used as only column constraint.

b). CHECK: This constraint provides a condition so that a value entered into the table has to satisfy
the condition. It can be used as columnconstraint or tableconstraint.

Eg: CREATE TABLE student (Rollno number(6) CHECK (Rollno>0));

2.Entity Integrity Constraints:

Entity Integrity ensures that there are no duplicate rows in a table. They maintain uniqueness in a table UNIQUE
and PRIMARY KEY are the entity integrity constraints.

a) UNIQUE: This constraint prevents duplicate values in the specified columns. However , it allows number
values in the column. It can be used as columnconstraint or tableconstraint.
Eg: CREATE TABLE student(Rollno number(6) UNIQUE);
b) PRIMARY KEY: This constraint prevents duplicate and null values in the specified column. However ,
only one primary key can be created for each table. It can be used as columnconstraints or
tableconsraint.

Eg: CREATE TABLE student (Rollno number(6) PRIMARY KEY);

3.Referential Integrity (Foreign key) Constraints:

The referential integrity constraint is a validation rule between two columns of same or different tables. It
allows values of a column into another column. It can be used as columnconstraint or tableconstraint.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

Eg: Parent Tabel:


CREATE TABLE student (Rollno number(4) PRIMARY KEY);

Child Table: (Columnconstraint)


CREATE TABLE Fee(Rollno number(4) REFERENCES student(Rollno), Amount number(8,2));

Child Table(Tableconstraint)
CREATE TABLE Fee(Rollno number(4), Amount number(8,2)),
FOREIGN KEY(Rollno) REFERENCES student(Rollno));

RELATIONSHIPS WITHIN THE RELATIONAL DATABASE

Relationships are used to represent association between 2 entities (or) more entities .In the design of relational
database, we can use different types of relationships. they are:-

1.One To One (1:1) relationship

2.One To Many (1:m) relationship

3.Many To Many(m:m) relationship

1. One-To-One Relationship:-In this relationship one instance of an entity is related to the one instance of
another entity.

Ex:A person is married to another person is a 1:1 relationship.

Is
marrie
d to

PERSO
N

The above relationship is shown in the relational model as:

2. One-To-Many Relationship:-In this relationship, one instance of an entity is related to many instances
of another entity.

Ex: The painter paints paintings are a one to many relationship.

PAINTER PAINTINGS
Paints

1
Zenex Vision Degree College DBMS –BCA- SEM-II

3. Many-To-Many (m:m) relationship:-In this relationship, many instances of an entity is related to the
many instances of another entity.

Ex : Employee teaches courses is a many-to-many relationship.

STUDENT COURSE
join

CODD’S RELATIONAL DATABASE RULES


Dr Edgar Frank Codd defined a set of 12 rules which qualify a database product as relational. These rules are
called Codd‟s rules. Any DBMS that satisfy these rules then the DBMS is said to be “fully relational”. The rules
are given below:
1. Information Rule
It states that all information in a relational database must be represented by values
2. Guaranteed Access Rule
It states that every value in the database must be accessed by combination of table name, Primary key a
Column name
3. Systematic Treatment of Nulls Rule
It states that there should be a systematic procedure in the use of nulls.
4. Online Catalogue Rule
It states that all the information within the catalogue (database) must be accessed with the same command.
5. Data Sub-Language Rule
It states that the RDBMS should have language that allows data definition, data manipulation, security
constraints, and transaction management operations.
6. View Updating Rule
It states that when the changes made in the view must be affected to its base table.
7. High-Level Insert, Update and Delete Rule
It states that the RDBMS should support insertion, updation and deletion of data at a table level le, a set of
records.
8. Physical Data Independence Rule
It states that the changes to the physical level (how the data is stored) must not require a change in
programs.
9. Logical Data Independence Rule
It states that changes to the logical level (adding columns, changing column lengths etc.) must not require
change in programs.
10. Integrity Independence Rule
It states that integrity constraints must be stored separately in the catalog. They must not include in
application programs.
11. Distribution Independence Rule
It states that the distribution of portions of the database to various locations should not be visible to users
of the database.
12. Non Subversion Rule
It states that if low level access is allowed to a system then it should not be able to subvert (damage) the
integrity rule to change data.

1
Zenex Vision Degree College DBMS –BCA- SEM-II

Entity Relationship Model

The Entity Relationship model is a detailed logical representation of the data for an organization. An E-R
model is normally expressed through E-R diagrams, which is a graphical representation of an E-R model. The E-R
model is expressed in terms of entities, relationships among these entities. Each entity has a set of attributes.

The basic notation for an E-R diagram is as follows:

Strong Entity Multi valued attribute

Derived attribute
Weak Entity

Relation ship

Associative entity
type Identifying relation ship

Attribute (simple& Single- valued)

Composit

E-R MODEL CONSTRUCTS (OR) COMPONENTS OF AN E-R MODEL

s a high level conceptual data model that shows graphical representation of entities, attributes and their relationships. It is developed by Pet
hey are

1. Entities

2. Attributes

3. Relationships

1. ENTITIES:- The fundamental unit in any data model is the entity. An entity is a person, object, place, thing or
event and so on about which the organisation wishes to maintain data. Each entity has set of attributes. We will
use rectangle symbol to define entity in database environment.

for example:-

PERSON STUDENT EMPLOYEE COURSE Entities

Entity type/Entity set:-An entity type is a collection of entities, that can share common properties (or)
characteristics. Each entity type in an E-r model is given a name with capital letters and in singular form .

2
Zenex Vision Degree College DBMS –BCA- SEM-II

Entity instance:-An entity instance is a single occurence of an entity type.

For example:-

Entity type:-STUDENT

Attributes:- Sno,Sname,Address,Fee...

16 Ramu Nellore 9000


entity instances
49 srinu Gudur 12000

Types of entities:-The entity types are of different types. They


are

1. Strong entity

2. Weak entity

3. Associative entity

Strong Entity: In an organization, most of the entity types are classified as strong entity types. A strong entity is
an entity, it has one primary key(identifier attribute) and that does not depends up on other entity. In E-R diagrams
strong entities are represented by rectangle symbol.

Eno Ename Salary

Identifier Attribute Entity


EMPLOYEE

Weak Entity: A weak entity is an entity, It has no primary key and that depends up on other entity. In E-R
diagrams weak entities are represented by double lined rectangle symbol. For example „DEPARTMENT‟ doesn‟t
contain a primary key. The weak entity has partial identifier attribute. It depends on the strong entity
„EMPLOYEE‟ called OWNER.

Eno Ename Dno Dname Dno

EMPLOYEE
hhaass DEPARTMENT

Strong Entity identifier relationship weak Entity

2
Zenex Vision Degree College DBMS –BCA- SEM-II

Associative entity:-An associative entity is nothing but an entity with relationship containing identifier attribute
(or ) not containing identifier attribute. It is represented by using the symbol

for example:-

ORDER ORDERLINE PRODUCT

associative entity

2.Attributes:-Each entity type is associated with a set of attributes. An attribute is nothing but a property (or) a
characteristic of an entity type. Each attribute is associated with a set of values called domain. We will use the
oval symbol to define an Attribute

for example:- Eno Ename attributes


Salary

EMPLOYEE
entity

[NOTE:The attributes are represented by giving a name with "initial capital letter" followed by lower case letters
with in the "ellipse symbol". If an attribute name consists of more than one word, we can use underscore symbol to
connect these words and we can start each word with a capital letter.]

Types of attributes:-The attributes are classified into different types. They

are:- 1.Simple attribute 5.Derived attribute

2. Composite attribute 6.simple identifier attribute

3.Single-Valued attribute 7.Composite identifier attribute

4.Multi-valued attribute

Simple Attribute: A simple attribute is an attribute that cannot be divided into smaller components is called
simple attribute. These attributes are represented by using ellipse symbol. For example, „Eno‟ is an attribute
cannot be divided into different components.

Composite Attribute: A composite attribute is an attribute that can be divided into smaller components is called
composite attribute. These.

For example, „Address‟ is an attribute can be divided into different components like Street, City, Pin etc. attributes
are represented by.

for example:-

2
Zenex Vision Degree College DBMS –BCA- SEM-II

Eno Ename Salary

EMPLOYEE
Address Composite attribute

Dno Street City Pin

Smaller components

Single valued Attribute: A single valued attribute is an attribute that have only one value of the entity instance.
For example, the entity type „EMPLOYEE‟ has an attribute „Salary‟, it takes only one value for a given entity
instance. So „Salary‟ is a single valued attribute. Single value attributes are represented by using ellipse symbol.

Multi valued Attribute: A multi valued attribute is an attribute that takes more than one value for a given entity
instance. In E-R diagrams multi valued attributes are represented by using double ellipse symbol.

Eno Ename
Salary Attributes

EMPLOYEE Skills

Entity Type Multi valued Attribute

Derived Attributes: A derived attribute is an attribute whose values can be calculated from other attribute values.
In E-R diagrams the derived attributes are represented by using dashed ellipse symbol. For example, the „Service‟
can be calculated from his „DOJ‟ .

Eno Ename DOJ

Service Derived Attribute


Entity EMPLOYEE

Identifier Attribute: An identifier attribute is an attribute that uniquely identifies individual entity instance of an
entity. It is represented by ellipse symbol, inside with single underlined. For example,

Eno Ename Salary

Identifier attribute EMPLOYEE Entity

2
Zenex Vision Degree College DBMS –BCA- SEM-II

Composite identifier attribute:-An identifier that consists of a composite attribute is called the composite
identifier attribute. It is represented by ellipse symbol, inside with double underlined.

for example:- Flight_ID Flightno


FLIGHT

Far
No_of_seat

3. Relationships:-A relationship is an association between two entities. In E-R diagram, the relationships are
represented by a diamond symbol containing the name of the relationship. In case of relationship between
strong and weak entities, we can use a diamond symbol with double line. For example:

Sno Sname Address C_Id Cname Fee

Completes
STUDENT COUR
SE

entity relationship entity

Note:Usually, a verb or preposition that connects two entities implies a relationship.

Types of Relationships:- Relationships are classified by their degree, connectivity, cardinality, existence. A
relationship between entities is described in terms of degree, connectivity, existence dependency, and cardinality.
Based on the degree, cardinalities, the relationships are mainly classified into two types. They are:-

1. Degree of the relationships.

2. Connectivity of the relationship

Degree of relationship:-The degree of a relationship is the number of entity types that participate in a relationship.
There are three types of relationship degrees in an E-R model. They are

1. Unary relationship
2. Binary relationship
3. Ternary relationship
Unary Relationship: An entity is associated itself is called unary relationship (or) recursive relationship. Its
degree=1.

Eno

Ename EMPLOYEE Manages

Salary

Binary Relationship: A relationship between two entities is called binary relationship. It is the most commonly
used relationship type in E-R model. Its degree=2.

2
Zenex Vision Degree College DBMS –BCA- SEM-II

EMPLOYEE COURSE
teaches

Ternary Relationship: A relationship between three entities is called ternary relationship. Its degree=3.

SUBJEC

Teaches STUDENT
TEACHE

The above relationship states that a teacher teaches a subject to a student.

Connectivity of Relationship: The connectivity describes the relationship classification. The relationship is
classified into one-to-one, one-to-many, many-to-many or many-to-one. The E-R diagram indicates the
relationship‟s connectivity by placing a 1, M or N near the related entities.

Connectivity refers to the number of entity instances. An entity instance is a particular occurrence of an entity.
There are 4 types of connectivity. They are one-to-one, one-to-many, many-to-many or many-to-one. The E-R
diagram indicates the relationship‟s connectivity by placing a 1, M or N near the related entities. For example, let
us assume X and Y are two entity sets then the relationship connectivity is as follows:

One-to-one Relationship :In this type, an entity in X is associated with at most one entity in Y, and an entity in Y
is associated with at most one entity in X.

Example:

1 1
EMPLOY Join DE
EE

The above relationship indicates that one employee has to join in only one department.

One-to-many Relationship: In this type, an entity in X is associated with any number of entities in Y. However,
an entity in Y is associated with at most one entity in X.

Eg:

DEP 1 N EMPLOYE E
Ha

2
Zenex Vision Degree College DBMS –BCA- SEM-II

The above relationship indicates that one department has many employees.

Many-to-one Relationship: In this type, an entity in X is associated with at most one entity in Y. However, an
entity in Y can be associated with any number of entities in X.

Eg:

EMPLOYEE N 1 DEP T
Joi

The above relationship indicates that many employees can join in only one department.

Many-to-many Relationship: In this type, an entity in X is associated with any number of entities in Y and an
entity in Y is associated with any number of entities in X.

Eg:

N N
TEACHE Teac STUDEN

The above relationship connectivity indicates that many teachers teach many students.

2
Zenex Vision Degree College DBMS –BCA- SEM-II

UNIT-3

INTRODUCTION TO ORACLE
ORACLE means “Oak Ridge Automated Computing Logical Engine”. Oracle is an Object Relational Database
Management System (ORDBMS) package. It offers capabilities of both relational and object-oriented database
system. The oracle provides various tools (or) products based on a technology called Client-Server technology. In
this technology, the server performs database activities and client help the user to interact with the database
application.
Tools of ORACLE: The oracle provides various tools. They are
1. SQL *PLUS
2. PL/SQL
3. FORMS
4. REPORTS
Here SQL *PLUS and PL/SQL are back-end tools(SERVER)
FORMS and REPORTS are front-end tools(CLIENT).
Structured Query Language (SQL)
Introduction:
Structured Query Language (SQL) is the standard set of commands used to access data within the
relational database. All tasks related to relational data management such as creating tables, querying the database
for information, modifying the data in the database, deleting them, granting access to users and so on can be done
using SQL.

History of SQL:
The language, Structured English Query Language (SEQUEL) was developed by IBM to use E.F.Codd’s
relational model. SEQUEL later became SQL. In 1979, Oracle Corporation introduced the first commercially
available implementation of SQL.
The American National Standards Institute (ANSI) and the International Standards Organization
(ISO) have accepted SQL as the standard language for relational databases. Today, SQL is widely accepted
standard RDBMS language. The SQL consists of a set of facilities for defining, accessing and managing relational
databases.
Characteristics (Features) of SQL:
1. SQL usage by its nature is extremely flexible. It uses a free form syntax that gives the user the ability
to write SQL statements in a easy way.
2. Each SQL command is analyzed by the RDBMS before execution, to check for proper syntax and
to process the command.
3. The SQL commands are very simple to write and easy to understand.

SQL LITERALS
A literal is a fixed value. It doesn‟t change its value. It is also called constant. In SQL, literals are classified
as follows:
LITERALS

NUMBER TEXT DAT

INTEGER FLOATING

2
Zenex Vision Degree College DBMS –BCA- SEM-II

Integer Literals:
Any number without fractional part is called an integer constant. The integer numbers can contain digits (0..9)
and sign (+ or -). An integer constant must not contain commas and spaces.
Eg: 3 -3 15 -15 2500 -9700 etc.
Text Literals:
A sequence of one or more characters enclosed within single quotes is called text literal. These are also known as
string literals or character strings;
Eg:
 „Nellore‟
 „SQL-99‟
 „Vikrama Simhapuri University‟
Date Literals:
Any date value enclosed within single quotes is called date literal. The date literals must be in the format „DD-
MON-YYYY‟.
Eg: ‟12-JUL-2022‟
SQL OPERATORS
An operator is a symbol or keyword used to perform arithmetic and logical operations. In SQL, operators are
classified into the following types. They are
1 Arithmetic operators
2 Relational (comparison)
operators 3 Logical operators
4 Set operators
5 Special relational operators
1 Arithmetic Operators: Arithmetic operators are used to perform mathematical operations likeaddition,
subtraction etc.
Operator Meaning Example Result
+ Addition 10+3 13
- Subtraction 10-3 7
* Multiplication 10*3 30
/ Division 10/3 3.333
10 | | 30 1030
|| Concatenation
10 | | „AB‟ 10AB

2 Relational (comparison) Operators: The relational operators compare two values and give the result either
true or false. These are used to form simple conditions.
Operator Meaning Example Result
> Greater than 50>40 T
< Less than 50<40 F
= Equal to 50=40 F
>= Greater than or equal to 50>=40 T
<= Less than or equal to 50<=40 F
!= Not equal to 50!=40 T

Logical Operators: The logical operators combine two conditions or to negate the result of a condition and give
the result either true or false. These are used to form compound conditions.

2
Zenex Vision Degree College DBMS –BCA- SEM-II

Operator Meaning Example Result


AND Gives true if both conditions are true 40>50 AND 50>30 F
OR Gives true if any or both conditions are true 40>50 OR 50>30 T
Gives true if condition is
NOT NOT (40>50) T
false Gives false if condition
is true

4 Set Operators:
Set operators are used to combine the output of two queries. These are used to form union queries.
Operator Meaning
UNION Returns all distinct rows from both queries
UNION ALL Returns all rows from both queries
INTERSECT Returns only common rows of both queries
MINUS Returns all rows of the first query but not in the second query

5 Special Comparison(Relational) Operators:


The special operators compare values and give the result either true or false. These operators will simplify the
complex conditions. They can be used in conditions.

Operator Meaning
IN Compares equal to any value in the list of values
BETWEEN Compares range of values
IS Compares nulls
LIKE Compares string patterns
ALL Compares all values within the list
ANY or SOME Compares any or some of values in the list

SQL DATA TYPES

The data type is the characteristic of a column in a table. It specifies the type of data to be entered into the column
of a table. The data types are used in creating a table structure. SQL data types are as follows
1 NUMBER data type: This data type allows numeric values
only. Syntax: NUMBER (L,D)
 L indicates length i.e. number of digits. D indicates the number of decimal places within the length
 The length should be in the range from 1 to 38 digits. The length is optional. If it is omitted, it takes
38 digits as default length.

Eg: i) number ii) number (9) iii) number (9,2)


2 CHAR data type: This data type allows any type of character i.e. alphabet, digit, or symbol. It stores
fixed length strings
Syntax : CHAR(size)
 The „size‟ indicates maximum number of characters allowed in each cell of column
 The „size‟ must be in the range from 1 to 2000 bytes
 The „size‟ is optional. If it is omitted, the default length is 1
character Eg: i) char ii) char(20)

2
Zenex Vision Degree College DBMS –BCA- SEM-II

3 VARCHAR2 data type: This data type allows any type of character i.e. alphabet, digit, or symbol. It
stores variable length strings.
syntax: VARCHAR(size)
 The „size‟ indicates maximum number of characters allowed in each cell of column
 The „size‟ must be in the range from 1 to 4000
bytes Eg: varchar2(20)
4 LONG data type: This data type allows any type of character i.e. „alphabet, digit, or symbol. It stores
variable length strings. It can store upto 2 Giga Bytes in each cell.
Syntax: LONG
Eg: long
5 DATE data type: This data type allows date values. Date values must be entered in „DD-MON-YYYY‟
format. Syntax: DATE
Eg: date
6 RAW data type: It is used to store small size multimedia information like images, audio and video. It stores
data in binary or hexadecimal format
Syntax: RAW(size)
 The „size‟ must be in the range from 1 to 255
bytes Eg: raw(100)
7 LONG RAW data type: It is used to store large size multimedia information like images, audio and video.
It stores data in binary or hexadecimal format.
Syntax: LONG RAW
Eg: long raw

TYPES OF SQL COMMANDS

The SQL commands are classified into the following categories:


1. Data Definition Language commands (DDL)
2. Data Manipulation Language commands (DML)
3. Data Control Language commands (DCL)
4. Transaction Control Language(TCL)
All the above languages are referred as sublanguages of SQL.
DDL commands:
These are used to define various database objects i.e. tables, views, indexes etc. We can create, modify,
delete and view the database objects by using these commands. The DDL commands are AutoCommit commands,
since they process and save objects automatically in the database. All commands starting with CREATE, ALTER,
DROP are treated as DDL commands.
Eg: CREATE TABLE, CREATE VIEW, ALTER TABLE, ALTER USER, DROP TABLE, DROP INDEX etc.
DML commands:
These commands are used to manipulate data within the ORACLE database. They are used to insert,
delete, update, and query the data in the database objects. These commands do not implicitly commit the current
transaction. SQL provides three data manipulation statements namely INSERT, UPDATE and DELETE.
DCL commands:
These commands are used to control user access to the database objects. They used to grant privileges(or
roles) to users and to cancel (or) remove privileges from the users. GRANT and REVOKE are treated as DCL
commands.

3
Zenex Vision Degree College DBMS –BCA- SEM-II

TCL commands:
Transaction Control language(TCL) commands manage changes made by Data Manipulation Language
commands. These commands are used to save or cancel the process of DML commands. COMMIT, ROLLBACK
and SAVEPOINT commands are treated as TCL commands.

TABLES

A table is one of the objects of Oracle database. It is the basic unit of data storage in a relational database
management system. Every table has a table name and a set of columns (fields) and rows (records) in which the
data is stored. Each column is identified by a column name and it is given a data type and width.
COLUMNS

EMPNO NAME DESIGNATION SALARY


RO

Logical Structure Of A Table

DDL COMMANDS (OR) ADVANCED DDL COMMANDS


The DDL(Data Definition Language) commands are used to define various database objects i.e. tables, views,
indexes etc. We can create, modify, delete and view the database objects by using these commands. The DDL
commands are AutoCommit commands, since they process and save objects automatically in the database. The
DDL commands supported by SQL are

1. Create table command


2. Alter table command
3. Drop table command
4. Truncate table command
5. Describe command

Create Table: In SQL, the database primary object is table. To create that tables we can use create table
command.
Syntax:
CREATE TABLE <table-name> (column data-type (size),...);
Ex:
SQL> CREATE TABLE books ( isbn number(3), bname varchar2(21), aname varchar2(21),price number(7,2));
SQL> CREATE TABLE product ( pcode varchar2(11), pname varchar2(21), mfd date);
SQL> create table empl ( eid number(5),ename varchar2(31), job varchar2(21),salary number(8,2), doj date);
NOTE:
Create Table Rules:
1. While naming a table the first letter must be an alphabet.
2. Oracle reserved words can't be used to name a table or column.

3
Zenex Vision Degree College DBMS –BCA- SEM-II

3. Maximum length for a table name is 30 characters.


4. Two different tables should not have the same name in same user.
5. Underscore, numerals and letters are allowed but not blank space, symbols.

Alter Table: The alter table command is used to change the structure of a database object(for ex: table).That
means you can add, modify, drop and rename columns of a table by using ALTER TABLE command. It is also
used to add constraints and remove constraints from the table.
Syntax: ALTER TABLE <table-name> [ADD | MODIFY] (Column data-type (size)...);
ALTER TABLE <table-name> DROP (column-names);
Adding new columns to a table:-
Ex: SQL> ALTER TABLE empl ADD(JOB VARCHAR2(11));
SQL> alter table books add(pubname varchar2(21),address varchar2(20));
Removing existing columns from a table:-
Ex: SQL> alter table empdet drop(doj); (or) sql>alter table empdet drop column doj;
SQL> alter table empdet drop(job,sal);
Modifying data type and width of existing columns in a
table:- Ex: SQL> alter table books modify (bname
varchar2(28));
SQL> alter table product modify(pcode number(5),pname char(20));
Changing the existing column name into new name:(works in sql 10g)
Syntax: alter table tablename rename column oldcolumnname to newcolumnname;
Ex: sql>alter table empl rename column eid to empid;
Rules for Adding Column:
1. You can't specify where the column is to appear. The new column becomes the last column in the table.
2. If a table already contains rows when a column is added, then the new column is initially null for all therows.
Rules for Drop Column:
1. The column may or may not contain data.
2. The table must have at least one column remaining in it after it is altered.
4. Once a column is dropped, it can't be recovered.
Rules Modify Column:
1. You can increase the width or precision of a numeric column.
2. You can increase the width of numeric or character column size.
3. You can decrease the width of a column only if the column contains null values or if the table has no rows.
4. You can change the data type only if the column contains null values (no values).
DROP TABLE Command:
The DROP TABLE command is used to remove (or) drop a table. When you drop a table, the database
loses the table and table data as well as the indexes associated with it.
Syntax:
DROP TABLE <table-name>;
Ex: SQL> drop table books;
Note: Once table is dropped can't be recovered.
TRUNCATE TABLE Command: It is used to remove all the data permanently but not the structure.
Syntax: truncate table tablename;
Ex: sql> truncate table bonus;
DESCRIBE command: It is one of DDL commands and is used to display the structure of the specified table. We
can also use this command to display the structure of a View or Synonym.
Syntax:
DESC[RIBE] objectname;
Here, the object name can be either table, view or synonym name which must be present in the
database. Eg: sql> DESCRIBE employee; (or) sql>DESC employee;

3
Zenex Vision Degree College DBMS –BCA- SEM-II

DML COMMANDS
The DML(Data Manipulation Language) commands are used to manipulate data within the ORACLE database.
They are used to insert, delete, update, and query the data in the database objects. The DML commands supported
by SQL are
1. INSERT Command
2. UPDATE Command
3. DELETE Command
4. SELECT Command
1. INSERT command: It is one of DML commands used to add one or more rows to a table. This command adds
the rows only at the end of the table. It doesn‟t insert any row in between existing rows of a table.
Method-1: Inserting Single Row:
INSERT INTO tablename VALUES ( values-list );
Here, the „tablename‟ specifies the name of the existing table. The „values-list‟ specifies the values that
are inserted into the table. The number and order (data type) of values in the „values-list‟ must match with the
number and order of columns of the table. All the values in the „values-list‟ must be separated by commas.
Eg:sql> INSERT INTO employee VALUES ( 1001,‟KUMAR‟,‟MANAGER‟,4500);
Method-2: Inserting values into particular columns: We can also insert values into the table in the specified
columns .
Syntax: INSERT INTO tablename ( column-list ) VALUES ( values-list );
Here, the „column-list‟ indicates the column names of the table. We can specify column names in
any order. The number and order (data type) of values in the „values-list‟ must match with the number and
order of columns in „column-list‟.
Eg: Sql>INSERT INTO employee (Empname, Joindate ) VALUES („XYZ‟, ‟12-JUN-89‟ );
Sql>insert into books values(&isbn,‟&bname‟,‟‟,&price);
Method-3: Inserting Multiple (bulk) Rows:
Syntax insert into tablename values(columnslist);
EX: sql> insert into books values (&isbn,‟&bname‟,‟&aname‟,&price );
[ NOTE:We can also insert multiple rows by retrieving records from another table using SELECT statement as
follows:
Method-1: INSERT INTO tablename query;
In the above syntax, the „tablename‟ is the name of the existing table in which we want to insert
the records. The „query‟ retrieves one or more rows from another table.
The number and order of columns in „query‟ must match to the number and order of columns of
the specified table.
Eg:
1. Sql>INSERT INTO sample SELECT * FROM employee;
2. Sql>INSERT INTO sample SELECT * FROM employee WHERE
job=‟CLERK‟; Method-2: INSERT INTO tablename(column-list) query;
In the above syntax, the „tablename‟ is the name of the existing table in which we want to insert
the records. The „query‟ retrieves one or more rows from another table.The number and order of columns
in „query‟ must match to the number and order of columns in the „column-list‟.
Sql>INSERT INTO newemp (ename, job) SELECT Empname, Job FROM emp;

Sql> INSERT INTO newemp (ename, job) SELECT Empname, Job FROM emp
WHERE sal>5000; ]not compulsory

3
Zenex Vision Degree College DBMS –BCA- SEM-II

2. UPDATE command:You can modify existing row or rows by using the UPDATE
command. Syntax: UPDATE <table-name> SET column1 = value1,… [WHERE
<condition>];
Ex: SQL> update EMP set ename='SURESH' where empno=7790;
Sql> update books set bname=‟oracle‟;
SQL> update student set total=cpp+vb+oracle;
SQL> update student set aveg=total/3;
SQL> update student set result='Pass' where result is null;
SQL> update student set result='Pass' where cpp>=35 and vb>=35 and
oracle>=35; SQL> update empdata set job=null where eid=102;
Note: The UPDATE statement modifies specific row or rows if the 'WHERE clause' is specified otherwise
modified all rows.

3. DELETE command:
It is one of DML commands used to delete the data from a table. We can use this command to remove all
the rows or specified rows from the table. However, we cannot delete a value or the values in a particular column.
Syntax:
DELETE [FROM] tablename [WHERE condition] ;
In the above syntax,
 The „tablename‟ is the name of the existing table,
 The WHERE clause is optional and is used to delete the table based on the given condition. If it is omitted, the
DELETE command will delete all the rows in the table.
Eg:
1. Sql>DELETE FROM student;
It deletes all rows from „student‟ table.
2. Sql> DELETE FROM student WHERE result =
„FAIL‟; It deletes rows from student table whose result
is „FAIL‟.
3. Sql>DELETE FROM employee WHERE job = „CLERK‟ and Joindate<‟12-MAR-89‟;
It deletes rows from employee who are joined before ‟12-MAR-89‟ and job is
„CLERK‟.

3
Zenex Vision Degree College DBMS –BCA- SEM-II

UNIT-4
QUERIES
The query is a process that retrieves required information from the database. The SELECT command is used to
query the database.
Uses of Queries:
1 To retrieve required data from one or more tables
2 To sort the data on multiple columns
3 To group the rows based on columns
4 To join data of multiple tables together
5 To find result of various expressions or
functions 6 To perform union operations

4. SELECT Command: It is also called as Query language command. It is used to display (or )query( or)
retrieve data from the table.
Syntax:
Select specific columns /* from tablename [where condition];
Here * means all columns.
Ex:1 sql>select *from books;
It displays all columns and all rows of a specified table.
Ex:2 sql>select *from books where bname=‟oracle‟;
It displays all columns and specific rows of a specified table.
Ex:3 sql>select isbn,bname from books ;
It displays specific columns and all rows of a specified table.
Ex:4 sql>select isbn,bname from books where price=200 ;
It displays specific columns and specificl rows of a specified table.

DISTINCT Clause: It eliminates duplicate values in the output. It displays only one value from the
duplicates. Eg: SELECT DISTINCT job FROM emp;

WHERE Clause: It is used to specify a condition using non-group values. When it is used, it retrieves all the
rows that match the given condition.
Eg: SELECT * FROM emp WHERE job=‟CLERK‟ AND salary<5000;
GROUP BY Clause: It is used to combine a group of rows based on the values of specified column(s). Eg:
SELECT JOB,COUNT(*) FROM employee GROUP BY job;
HAVING Clause: It is used to specify a condition using aggregate(group)functions.
Eg: SELECT JOB, COUNT(*) FROM employee GROUP BY job HAVING COUNT(*)>3;
ORDER BY Clause: It is used to display rows either in ascending or descending order based on the specified
columns. The keyword DESC is used to display rows in descending order. If it is omitted,
SELECT command displays rows in ascending order.
Eg:
1. SELECT * FROM emp ORDER BY salary;
2. SELECT * FROM emp ORDER BY salary DESC;

3
Zenex Vision Degree College DBMS –BCA- SEM-II

DATA INTEGRITY CONSTRAINTS/DATA INTEGRITY RULES

An integrity constraint is a condition used to prevent invalid data entry into the table. It enforces rules for
the columns in a table.
Syntax to define constraints:
CREATE TABLE tablename ( column datatype(size) [CONSTRAINT constraintname] constrainttype, ….);
Where „constrainttype‟ is one of the following:
NOT NULL,CHECK,UNIQUE,PRIMARY KEY,FOREIGN KEY…REFERENCES
The „constraintname‟ is a user-defined word which is used to give name to the above constraints. If it is
omitted, SQL gives default constraint name starting with SYS_C followed by a number like SYS_C00123. These
constraint names are used to drop constraints.

Types of Constraints:
There are three types of constraints in SQL to maintain integrity.
1. Domain Integrity Constraints
2. Entity Integrity Constraints
3. Referential Integrity (Foreign Key) Constraints
1. Domain Integrity Constraints: Domain Integrity enforces valid entries for a given column by restricting
the format or the range of possible values. NOT NULL and CHECK constraints are the domain constraints.
NOT NULL: This constraint enforces that the column will not accept null values. By default, all the columns in a
table allow null values. It must be used only at column level.
Eg:
SQL>CREATE TABLE student ( Rollno Number(5) CONSTRAINT rno NOT NULL,
Stname Varchar2(25) NOT NULL, Course Varchar2(4) );
In the above example, the columns Rollno and Stname do not allow null values, but Course column allows
null values.
CHECK: This constraint provides a condition so that a value entered into the table has to satisfy the condition
before it is stored. The CHECK constraint consists the keyword CHECK followed by a condition within
parenthesis. While insert or update, any invalid value entered then this constraint will give an error.
Eg:
SQL> CREATE TABLE student( Rollno Number(4),Stname Varchar2(25) NOT NULL,
Course Varchar2(4) CHECK (Course IN(„BCOM‟,‟MSCS‟)));

2. Entity Integrity Constraints: These are used to prevent duplicate rows in a table.UNIQUE and PRIMARY
KEY are the entity integrity constraints.
UNIQUE:
This constraint prevents duplicate values while inserting or updating the values in the specified set of
columns. However, it allows null values into the column. It can be used to more than one column. It can be
specified for a maximum of 16 columns. This constraint can be used at column or table level.
Eg-1:(Column Level)
Sql>CREATE TABLE student( Rollno Number(4) UNIQUE,Stname Varchar2(25) NOT NULL, Course
Varchar2(4) );
Eg-2:(Table Level)
Sql>CREATE TABLE student( Rollno Number(4),
stname Varchar2(25) NOT NULL,Course Varchar2(4),UNIQUE(Rollno));
We can use UNIQUE constraint for multiple columns only at table level.
Eg: sql>CREATE TABLE student( Rollno Number(4), Stname Varchar2(25) NOT
NULL, Course Varchar2(4),UNIQUE(Rollno, Course));

3
Zenex Vision Degree College DBMS –BCA- SEM-II

PRIMARY KEY: This constraint prevents duplicate and null values while inserting or updating the values in the
specified set of columns. Every table should have a primary key constraint to uniquely identify each row.
However, only one primary key constraint can be created for each table.
The Primary Key constraint can be used for a single column at column or table level or for multiple
columns at table level. When Primary Key constraint is specified for multiple columns then it is said to be
composite primary key. It can contain a maximum of 16 columns.
Eg-1:(Column Level)
Sql>CREATE TABLE student( Rollno Number(4) PRIMARY KEY,
Stname Varchar2(25) NOT NULL, Course Varchar2(4) );
Eg-2:(Table Level)
SQL>CREATE TABLE student( Rollno Number(4), Stname Varchar2(25) NOT NULL,
Course Varchar2(4), PRIMARY KEY(Rollno));
Eg-3:(Composite Primary Key)
SQL>CREATE TABLE student( Rollno Number(4),
Stname Varchar2(25) NOT NULL,Course Varchar2(4),PRIMARY KEY(Rollno, Course));

3. Referential Integrity (Foreign Key) Constraints:


The referential integrity constraint is a validation rule between two tables that are having a common
column. It establishes a parent-child or master-detail relationship between two tables.
To implement this type of constraint, parent table must contain primary key or unique column and the
same column in the child table as foreign key that refers to the corresponding parent tableentry.
Eg:
Parent Table:
SQL>CREATE TABLE student( Rollno Number(4) PRIMARY KEY,
Stname Varchar2(25) NOT NULL,Course Varchar2(4));
Child Table:
SQL>CREATE TABLE marks( Rollno Number(4) REFERENCES student(Rollno),
Sub1 Number(3), Sub2 Number(3), Sub3 Number(3),Total Number(3));
(OR)
SQL>CREATE TABLE marks( Rollno Number(4), Sub1 Number(3), Sub2 Number(3), Sub3
Number(3), Total Number(3),FOREIGN KEY(Rollno) REFERENCES student(Rollno));
ON DELETE CASCADE: This optional clause is used to delete child table entries when parent table entry is
deleted.
Eg:
SQL> CREATE TABLE marks( Rollno Number(4), Sub1 Number(3), Sub2 Number(3),
Sub3 Number(3), Total Number(3),
FOREIGN KEY(Rollno) REFERENCES student(Rollno) ON DELETE CASCADE);

Adding constraints to the existing table:


ALTER TABLE command is used to add constraints to the existing table.
SYNTAX:
ALTER TABLE tablename modify/add constraint constraintname
constrainttype(columnnames);
Ex: sql>ALTER TABLE student MODIFY(Stname NOT
NULL); Sql>ALTER TABLE student ADD(CHECK (Rollno > 0));
Sql>ALTER TABLE student ADD(PRIMARY KEY(Rollno));
Sql>ALTER TABLE student ADD(UNIQUE(Rollno));
Sql>ALTER TABLE student ADD(FOREIGN KEY(Rollno) REFERENCES student(Rollno));

3
Zenex Vision Degree College DBMS –BCA- SEM-II

Dropping Constraints: ALTER TABLE command is used to drop constraints from the specified table.
Syntax:
ALTER TABLE tablename DROP CONSTRAINT constraint_name ;
In the above syntax, the „constraint_name’ is a name given to the constraint.
Eg: 1.Sql>ALTER TABLE employee DROP CONSTRAINT SYS_C00235 ;
Sql>ALTER TABLE student DROP CONSTRAINT fk_stno;

Displaying constraint details:


Syntax:
select specific columns/ * from user_constraints
[where table_name=‟tablename in capital letters‟];
Ex: sql>select constraint_name,constraint_type,search_condition from user_constraints where
table_name=‟STUDENT‟;
SUB-QUERIES

A query within another query is called sub-query. It is also known as nested query. It is a technique used to
process multiple tables that involves placing an inner query (SELECT…FROM…WHERE) within WHERE or
HAVING clause of another (outer) query. The inner query provides values for the condition of the outer query. An
outer query or inner query can have multiple sub-queries.
Rules for using subqueries:
1. The inner query must be specified on the right hand side of the condition.
2. The inner query must be enclosed within parenthesis
3. Proper comparison operator must be used in the outer query‟s condition based on the output of inner query.

Types of subqueries:
There are two types of sub-queries used in SQL. They are nested sub-query and correlated sub-query.
1. Nested sub-query:
It is the most commonly used sub-query. A nested sub-query is classified into single row sub-query and
multiple row sub-query.
Single row subquery:
When the inner query returns only one row (value) to the outer query then it is called single row sub-query.
Eg: List employee details whose job is Kumar‟s job.
Sql>Select * From Emp Where Job = (Select Job From Emp Where Empname=‟KUMAR‟);
Multiple row subquery:
When the inner query returns multiple rows (values) to the outer query then it is called multiple row sub-
query.
Eg-1: List employee details whose job is Kumar‟s or John‟s job.
Sql>Select * From Emp Where Job = (Select Job From Emp Where Empname
In(‟KUMAR‟,‟JOHN‟)); Eg-2: List employee details whose salary is greater than any manager‟s salary
Sql>Select * From Emp Where salary > any (Select salary from emp where job=‟manager‟);
2. Correlated sub-query : It is a subquery, that executes once for each row in the outer query. The execution of
correlated subquery is similar to the execution of the nested loop in a programming language.
For EX: for(i=1;i<=2;i++) outer loop
For(j=1;j<=3;j++) inner loop
Printf(“i=%d j=%d”,I,j);

3
Zenex Vision Degree College DBMS –BCA- SEM-II

o/p: i=1 j=1 i=2 j=1


i=1 j=2 i=2 j=2
i=1 j=3 i=2 j=3
Eg: List employee details whose salary is greater than their department‟s average salary.
Sql>Select * From Emp A Where salary > (Select avg(salary) from emp B
where B.Deptno=A.Deptno);
NOTE:1) It initiates the outer query.
2) For each row of the outer query, it(correlated subquery)executes the inner query by passingthe outer row
to the inner query.

SQL WITH SPECIAL OPERATORS

Special Comparison (Relational) Operators:


These operators are only available in SQL and are used in conditions. These operators will simplify the
complex conditions. These are as follows:

Operator Meaning
IN Equal to any member of the list
IS null Test for nulls
LIKE Test for pattern
BETWEEN Test for range of values
ALL Compares every value of a suquery
ANY or SOME Compares each value of a subquery
EXISTS True if subquery returns at least one row

BETWEEN: This operator is used to check whether a value is present in the specified range of values or not.
Syntax: Operand [NOT] BETWEEN x AND y
Eg.sql> SELECT * FROM EMP WHERE SAL BETWEEN 2500 AND 5000;
IN: This is used to check whether a value is present in the set of values or not.
Syntax: Operand [NOT] IN (Values)
Eg.: sql>SELECT * FROM EMP WHERE JOB IN(„CLERK‟,‟MANAGER‟);
LIKE: This operator is used to check for pattern matching for the character data type values. It uses wild card
characters (% , _ ) to check pattern matching. The character „%‟ represents any number of characters
and underscore „_‟ represents single character.
Syntax : Operand [NOT] LIKE pattern-string
Eg:
1. Sql>SELECT * FROM EMP WHERE ENAME LIKE „SM%‟
2. Sql>SELECT * FROM EMP WHERE ENAME LIKE „_ _ A
%‟ IS null: This operator is used to compare null values only.
Eg:sql> SELECT * FROM EMP WHERE JOB IS NULL;
ANY or SOME: This operator is used to compare a value to each value returned by a subquery. It returns true if
any of the values match the condition. It must be used along with comparison operator i.e. >, <, = etc.
Syntax : Operand [NOT] relational-opearator ANY (subquery)
Eg: sql>SELECT * FROM EMP WHERE SAL > ANY(SELECT SAL FROM EMP WHERE JOB=‟MANAGER‟)
ALL: This is used to compare a value to every value returned by a subquery. It returns true if all the values match
the condition. It must be used along with comparison operator i.e. >, <, = etc.
Syntax : Operand [NOT] relational-opearator ALL (subquery)
Eg:sql> SELECT * FROM EMP WHERE SAL > ALL(SELECT SAL FROM EMP WHERE JOB=‟MANAGER‟)

3
Zenex Vision Degree College DBMS –BCA- SEM-II

EXISTS: This operator returns true if the subquery returns atleast one row.
Eg.:SQL> SELECT * FROM EMP WHERE EXISTS (SELECT * FROM DEPT);
3. Logical Operators (or) Compund operators:
These operators are used to combine two or more conditions or to negate the result of a condition. These
are as follows:
Operator Meaning
AND Returns true if both conditions are true
OR Returns true if either conditions are true
NOT Negates the result of a condition
4. Set Operators (or) union operators:
Set operators are used to combine the results of two separate queries into a single result. These are as
follows:

Operator Meaning
UNION Returns all distinct rows from both queries
UNION ALL Returns all rows from both queries
INTERSECT Returns only common rows of both queries
MINUS Returns all distinct rows of the first query but not in the second one.

GROUP FUNCTIONS (OR)AGGREGATE FUNCTIONS

The aggregate functions are also known as group functions. They perform a task on a group of items and
produce a single value for the entire group. The group functions supported by SQL are
SUM()
AVG()
MAX()
MIN()
COUNT()

SUM( ):
This function returns the sum of values of the specified column by ignoring null values. It must be used for
number datatype columns only.
Syntax: SUM([DISTINCT/ALL] column)
Eg-1: SQL>Select sum(salary) from emp;
This example returns the sum of values of salary column by ignoring nulls.
AVG( ):
This function returns the average of values of the specified column by ignoring null values. It must be used
for number datatype columns only.
Syntax: AVG([DISTINCT/ALL] column)
Eg-1: SQL>Select avg(salary) from emp;
This example returns the average of values of salary column by ignoring nulls.
Eg-2: SQL>Select avg(distinct sal) from emp;
This example returns the average of values of salary column by ignoring null and duplicate values.

4
Zenex Vision Degree College DBMS –BCA- SEM-II

MAX( ):
This function returns the maximum value from the values of the specified column by ignoring null values.
It can be used for any datatype column.
Syntax: MAX([DISTINCT/ALL] column)
Eg: SQL>Select MAX(salary) from emp;
This example returns the maximum value of salary column by ignoring nulls.
MIN( ):
This function returns the minimum value from the values of the specified column by ignoring null values.
It can be used for any datatype column.
Syntax: MIN([DISTINCT/ALL] column)
Eg-1: SQL>Select MIN(salary) from emp;
This example returns the minimum value of salary column by ignoring nulls.
COUNT():
This function is used to count number of values. It is used in 3 ways.
They are COUNT(*)
COUNT(COLUMNNAME)
COUNT(DISTINCT COLUMNNAME)

COUNT(*):-This function counts the number of rows present in the specified table including duplicates and nulls.
Eg:SQL> Select count(*) from emp;
COUNT(columnname):-This function counts the number of values present in the specified column by ignoring null
values. It can be used for any datatype column.
Eg-1:SQL> Select count(salary) from emp;
This example counts the no. of values present in salary column by ignoring nulls.
COUNT(DISTINCT COLUMNNAME):It counts the number of values without including nulls and
duplicates.That means counts the distinct values of the specified column.
Eg-1: Select count(distinct sal) from emp;
This example counts the no. of values present in salary column by ignoring null and duplicate
values.

RELATIONAL SET OPERATORS (OR) UNION OPERATORS


(UNIONS)

The set operators are used to combine the output of multiple queries into a single result. There are 4 types
of set operators used in SQL. They are UNION, UNION ALL, INTERSECT and MINUS.
While working with set operators, the following points should be remembered.
1. The queries that are combined by the set operator must have same number and order of columns.
2. The queries must not contain Long datatype columns.
3. The first query labels (headings) are displayed as column headings in the output.

Syntax:
Query1 SetOperator Query2 SetOperator Query3 …….;
Let us assume EXAM1 and EXAM2 contain data as follows:

4
Zenex Vision Degree College DBMS –BCA- SEM-II

EXAM1 EXAM2
RNO NAME MARKS RNO NAME MARKS
101 A 40 101 A 80
102 B 80 103 C 90
104 D 90 105 E 58
105 E 75 107 G 85
106 F 95 108 H 95

UNION Operator:
This operator returns all the distinct rows selected by both queries. The output contains sorted data based
on the selected columns in the query.

Eg:
Sql>Select RNO, NAME from EXAM1 UNION Select RNO, NAME from EXAM2;

Output:
RNO NAME
101 A
102 B
103 C
104 D
105 E
106 F
107 G
108 H

UNION ALL Operator:


This operator returns all the rows selected by both queries including duplicate rows. The output contains
all the rows of the first query followed by all the rows of the second query.
Eg:
Sql>Select RNO, NAME from EXAM1 UNION ALL Select RNO, NAME from EXAM2;
Output:
RNO NAME
101 A
102 B
104 D
105 E
106 F
101 A
103 C
105 E
107 G
108 H

4
Zenex Vision Degree College DBMS –BCA- SEM-II

INTERSECT Operator:
This operator returns only common rows selected by both queries including duplicate rows.
Eg:
Sql>Select RNO, NAME from EXAM1 INTERSECT Select RNO, NAME from EXAM2;
Output:
RNO NAME
101 A
105 E
MINUS Operator:
This operator returns all the distinct rows selected by first query, but not contain in the second query.
Eg:
1. Sql>Select RNO, NAME from EXAM1 MINUS Select RNO, NAME fromEXAM2;
2. Sql>Select RNO, NAME from EXAM2 MINUS Select RNO, NAME from EXAM1;

Output: ex:1 ex:2


RNO NAME MARKS RNO NAME MARKS
102 B 80 103 C 90
104 D 90 107 G 85
106 F 95 108 H 95

JOINING DATABASE TABLES


(SQL JOIN OPERATORS)

A join is a relational operation (query) that combines data of two or more tables into single result table using a
common column. It is the most frequently used relational operation to process multiple tables.

Types of Joins: There are several types of joins used in relational databases. Some of them are:

1. Cartesian Join (Cross Join)


2. Natural Join
3. Inner Join
4. Outer Join

Let EMP and DEPT tables have the data as follows:

EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION
1001 RAJESH 20 10 ACCOUNTS DELHI
1002 JESSIE 10 20 RESEARCH CHENNAI
1003 VANI 10 30 SALES BANGALORE
1004 KAVITHA 40

4
Zenex Vision Degree College DBMS –BCA- SEM-II

1) CARTESIAN JOIN:
When multiple tables are joined without any condition then it is called Cartesian join. It is also called
Cross Join. It combines all rows of one table with every row of the other table. As a result, it returns the
Cartesian product
For example, if a table contains 10 rows and other contains 5 rows then the Cartesian product is 50 rows.
Syntax:
SELECT */columnlist FROM table1 CROSS JOIN table2;

Eg: SELECT * FROM emp CROSS JOIN dept;

EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION


1001 RAJESH 20 10 ACCOUNTS DELHI
1002 JESSIE 10 10 ACCOUNTS DELHI
1003 VANI 10 10 ACCOUNTS DELHI
1004 KAVITHA 40 10 ACCOUNTS DELHI
1001 RAJESH 20 20 RESEARCH CHENNAI
1002 JESSIE 10 20 RESEARCH CHENNAI
1003 VANI 10 20 RESEARCH CHENNAI
1004 KAVITHA 40 20 RESEARCH CHENNAI
1001 RAJESH 20 30 SALES BANGALORE
1002 JESSIE 10 30 SALES BANGALORE
1003 VANI 10 30 SALES BANGALORE
1004 KAVITHA 40 30 SALES BANGALORE

2 NATURAL JOIN:

It returns rows of two tables that are having matching values in the matching columns. It eliminates duplicate
columns in the result. The matching columns must have the same names and data types. But if there are no
common columns then it returns cross product.

Syntax: SELECT */columnlist FROM table1 NATURAL JOIN table2;

Eg: SELECT * FROM emp NATURAL JOIN dept;

Output:

DEPTNO EMPNO ENAME DNAME LOCATION


10 1002 JESSIE ACCOUNTS DELHI
10 1003 VANI ACCOUNTS DELHI
20 1001 RAJESH RESEARCH CHENNAI

3 INNER JOIN: An inner join returns all rows matching the join condition. It returns rows of two tables that
are having matching values in the specified columns of the join condition. It is like natural join but it is useful
when there are no common in the tables.

Syntax: SELECT */Columnlist FROM table1 INNER JOIN table2 ON joincondition;

Eg:

4
Zenex Vision Degree College DBMS –BCA- SEM-II

SELECT * FROM emp INNER JOIN dept ON emp.deptno=dept.deptno;

Output:

EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION


1002 JESSIE 10 10 ACCOUNTS DELHI
1003 VANI 10 10 ACCOUNTS DELHI
1001 RAJESH 20 20 RESEARCH BANGALORE

4. OUTER JOINS:

An outer join returns all matching and non-matching rows. There are three types of outer joins. They are

LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN.

i) LEFT OUTER JOIN: The left outer join returns all matching rows followed by non-matching rows
of left side table.

Syntax: SELECT */columnlist FROM table1 LEFT OUTER JOIN table2 ON joinconditon;

Eg: SELECT * FROM emp LEFT OUTER JOIN dept ON emp.deptno = dept.deptno;

Output:

EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION


1002 JESSIE 10 10 ACCOUNTS DELHI
1003 VANI 10 10 ACCOUNTS DELHI
1001 RAJESH 20 20 RESEARCH CHENNAI
1004 KAVITHA 40 SALES BANGALORE

ii) RIGHT OUTER JOIN: The right outer join returns all matching rows followed by non-matchingrows
of right side table.

Syntax: SELECT */columnlist FROM table1 RIGHT OUTER JOIN table2 ON joincondition;

Eg: SELECT * FROM emp RIGHT OUTER JOIN dept ON emp.deptno= dept.deptno;

Output:

EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION


1002 JESSIE 10 10 ACCOUNTS DELHI
1003 VANI 10 10 ACCOUNTS DELHI
1001 RAJESH 20 20 RESEARCH CHENNAI
30 SALES BANGALORE

4
Zenex Vision Degree College DBMS –BCA- SEM-II

iii) FULL OUTER JOIN: The full outer join returns all matching rows followed by non-matching rows of
either side table.

Syntax: SELECT */columnlist FROM table1 FULL OUTER JOIN table2 ON joincondition;

Output:

EMPNO ENAME DEPTNO DEPTNO DNAME LOCATION


1002 JESSIE 10 10 ACCOUNTS DELHI
1003 VANI 10 10 ACCOUNTS DELHI
1001 RAJESH 20 20 RESEARCH CHENNAI
1004 KAVITHA 40 30 SALES BANGALORE

SQL FUNCTIONS

A function is a predefined formula that returns a value using its parameters. In SQL, the functions are classified as
follows:

1). Date functions

2). Numeric functions

3). String functions

4). Conversation functions

DATE FUNCTIONS:

1). SELECT SYSDATE FROM DUAL;

2). ADD_MONTHS (Date, No.of months)

Eg: SELECT ADD_MONTHS(‟02-FEB-81‟,3) FROM DUAL;

3). LAST_DATE() it returns a date of the last day of the month given in a date.

4). MONTHS_BETWEEN() it returns the number of months between the given two

dates. Eg: SELECT MONTHS_BETWEEN(‟02-JUN-81‟,‟02-FEB-81‟) FROM DUAL;

NUMERIC FUNCTIONS:

1. SQRT() it returns square root of a


given number. Eg: SQRT(number)

2 . POWER(number1,number2)

Eg: SELECT POWER (2,4) FROM DUAL;

3 ROUND (number, precision)

4
Zenex Vision Degree College DBMS –BCA- SEM-II

Eg: ROUND (243.569,1) FROM DUAL;

4 TRUC() it truncates (removes) fractional part of a

number Eg: TRUNC(number)

SELECT TRUNC (243.569 FROM DUAL;

STRING FUNCTIONS

LENGTH () it returns the length of a string

Eg: SELECT LENGTH („COMPUTER‟) FROM DUAL;

LOWER (); it converts uppercase string into the lowercase string

LOWER(string)

UPPER (string)

SUBSTR (string): it returns a substring of a given string Substring

(string, position, no. of characters)

SELECT SUBSTR(COMPUTER‟,3,2) FROM DUAL;

CONVERSATION FUNCTIONS: These are used to convert a value in one data type into another data type.

1. TO_CHAR(): It converts a numeric value into specified stringformat

Syntax: TO_CHAR (value, format)

Format codes:

Code Meaning
9 Digit
0 Leading Zero
, Comma
$ Dollar Sign
Eg: SELECT TO_CHAR („$9,999.99‟) FROM DUAL; output: $2,650.00

2.TO_NUMBER (): it is used to convert a formatted number from a character string using a given format or
to convert a character value into number value.

Syntax: TO_NUMBER (string value, format)

Eg: SELECT TO_NUMBER(„$2,650‟,‟$9,999‟) FROM DUAL;

4
Zenex Vision Degree College DBMS –BCA- SEM-II

VIEWS

A view is a database object which is created from a query that uses one or more base tables. The views are also
known as virtual or logical or derived tables. Using SQL queries, views are created using base table‟s data.
A view doesn‟t contain data; instead it derives its data from the base tables. A view can also be used in the same
way as base table is used. But the changes are made in their base tables.

Merits:

1). Views simplify query commands


2). They help to establish data
security 3). They retrieve most current
space 4). They use little storage space
5). They can be used to hide complex queries

Demerits:

1). A view uses recreating time, each time it is referenced


2). A view may not be updated directly

Types of Views:
They are two types of views namely Updatable and Non-Updatable views
Updatable Views: The views that allow data manipulation then they are called Updatable Views. If any DML
operation performed on view will affect to its base table. But, some rules must be followed to create updatable
views.
Non-Updatable Views: The views that do not allow data manipulation then they are called Non-Updatable
Views.
Creation of views: The DDL command CREATE VIEW is used to create views.
Syntax:
CREATE [OR REPLACE] VIEW viewname AS query;

Eg:
1. CREATE VIEW clerkinfo AS SELECT * FROM emp WHERE job=’CLERK’;
2. CREATE OR REPLACE VIEW clerkinfo AS SELECT * FROM emp WHERE job=’CLERK’;
DML operations on Views:
Once a view is created, we can do various DML operations on views. Any DML operation performed on
view will affect to its base table.
Eg:
1. INSERT INTO clerksinfo VALUES(1001,’XYZ’,’CLERK’,3000);
2. UPDATE clerksinfo SET sal=4000 WHERE sal=3000;
3. DELETE FROM clerksinfo;
4. SELECT * FROM clerkinfo;
Dropping Views:
DROP VIEW command is used to remove views from the database. When a view is dropped, it doesn’t
affect to the base table data.
Syntax: DROP VIEW
viewname; Eg: DROP VIEW
clerkinfo;

4
Zenex Vision Degree College DBMS –BCA- SEM-II

DCL COMMANDS

Data Control Language commands are used to control user access to the database objects. These are used to
provide authorization to protect the data in the database. Authorization is permission given to user to access an
object. This can be done by granting or removing various privileges or roles.
PRIVILEGES: A privilege is a permission to execute an SQL statement or to access another user’s object. The
user can access objects based on the privileges they received.
Eg: INSERT, SELECT, UPDATE etc (DML).
ROLES: A role is a named set of privileges given to users. Roles are defined to manage the privileges for a user
group.
Eg: CONNECT, RESOURCE, DBA etc.

GRANTING AND REVOKING PRIVILEGES AND ROLES


GRANT command:
It is one of DCL command used to grant privileges or roles to users. The owner or grantee can grant
privileges to other users.
Syntax:
1. GRANT ALL/ Rolelist to PUBLIC(All users) / userlist;
2. GRANT ALL/ privilegelist ON object TO PUBLIC/userlist;
In the above syntax,
i). All means all the roles or
privileges ii). Rolelist means role
names
iii). Privilegelist means privilege names
iv).Object is a table, view etc.
v). PUBLIC means all users
vi).Userlist means user names
examples:
1. GRANT CONNECT TO USER1;
2. GRANT SELECT ON EMP TO USER1;
REVOKE command:
It is one of DCL command used to remove privileges or roles from users. The owner or grantee can remove
privileges from other users.

In the above syntax,


i). ALL means all the roles or
privileges ii). Rolelist means role
names
iii). Privilegelist means privilege names
iv). Object is a table, view etc.
v). PUBLIC means all users
vi). Userlist means user names
examples:
1. REVOKE CONNECT FROM USER1;
2. REVOKE SELECT ON EMP FROM USER1;

4
Zenex Vision Degree College DBMS –BCA- SEM-II

UNIT-5

PL/SQL

Introduction: PL/SQL stands for procedural language/Structured Query language.


This is the advanced for SQL and extension for SQL. The PL/SQL fulfills the disadvantages of SQL. By using
PL/SQL user can pass set of SQL statements to oracle engine.
Advantages of PL/SQL:
PL/SQL has several advantages rather than SQL.
They are
1. PL/SQL is a programming language.
2. It is structured programming language.
3. It is a simple programming language
4. It is a modular programming language.
5. It supports all tips of control statements.
6. It supports cursor programming.
7. It supports data security by writing triggers.
8. It supports user defined procedures, functions and packages.
9. It supports logical error detection by using exception handling.

10. PL/SQL also works like front end tool.

Structure of PL/SQL Block

In PL/SQL, the code is not executed in single line format, but it is always executed by grouping the code into a
single element called Blocks.

PL/SQL is the procedural approach to SQL in which a direct instruction is given to the PL/SQL engine about
how to perform actions like storing/fetching/processing data. These instructions are grouped together
called Blocks.

Blocks contain both PL/SQL as well as SQL instruction. All these instruction will be executed as a whole rather
than executing a single instruction at a time.

Block Structure

PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are different sections of
PL/SQL blocks

1. Declaration section
2. Execution section
3. Exception-Handling section

5
Zenex Vision Degree College DBMS –BCA- SEM-II

Declaration Section

This is the first section of the PL/SQL blocks. This section is an optional part. This is the section in which the
declaration of variables, cursors, exceptions, subprograms, instructions and collections that are needed in the block
will be declared. Below are few more characteristics of this part.

 This particular section is optional and can be skipped if no declarations are needed.
 This should be the first section in a PL/SQL block, if present.

 This section starts with the keyword 'DECLARE' for triggers and anonymous block. For other
subprograms this keyword will not be present, instead the part after the subprogram name definition
marks the declaration section.
 This section should be always followed by execution section.

Execution Section

Execution part is the main and mandatory part which actually executes the code that is written inside it. Since the
PL/SQL expects the executable statements from this block this cannot be an empty block, i.e., it should have at
least one valid executable code line in it. Below are few more characteristics of this part.

 This can contain both PL/SQL code and SQL code.


 This can contain one or many blocks inside it as a nested blocks.
 This section starts with the keyword 'BEGIN'.
 This section should be followed either by 'END' or Exception-Handling section (if present)

Exception-Handling Section:

The exceptions are unavoidable in the program which occurs at run-time and to handle this Oracle has provided an
Exception-handling section in blocks. This section can also contain PL/SQL statements. This is an optional section
of the PL/SQL blocks.

5
Zenex Vision Degree College DBMS –BCA- SEM-II

 This is the section where the exception raised in the execution block is handled.
 This section is the last part of the PL/SQL block.
 Control from this section can never return to the execution block.
 This section starts with the keyword 'EXCEPTION'.
 This section should be always followed by the keyword 'END'.

The Keyword 'END' marks the end of PL/SQL block.

Data Types in PL/SQL

Data Type: Data Type specifies the type of the data which can be stored in the specified variable. PL/SQL
supports the same data types of SQL and its supports some other data types. They are

1. Scalar data types - Scalar data types haven't internal components.


2. Composite data types - Composite data types have internal components to manipulate data easily.
3. Reference data types - These data types works like a pointer to hold some value.
4. LOB data types - Stores large objects such as images, graphics, video.
5. Unknown Column types - Identify columns when not know type of column.
6. User Define data types - Define your own data type that are inherit from predefined base data type.

Scalar types

Scalar data type haven't internal components. It is like a linear data type. Scales data type divides into four
different types character, numeric, boolean or date/time type.

5
Zenex Vision Degree College DBMS –BCA- SEM-II

NUMBER data type used to store numeric data.


It's contain letters, numbers, and special characters.
Storage Range : Precision range(p) : 1 to 38 and Scale range(s) : -84 to 127
NUMBER Subtypes : This sub type defines different types storage range.
Sub Data types Maximum Precision Description
INTEGER 38 digits
INT 38 digits
SMALLINT 38 digits
NUMBER(p,s) DEC 38 digits
DECIMAL 38 digits
This data types are used to store fixed
NUMERIC 38 digits decimal points. You can use based on
REAL 63 binary digits your requirements.
DOUBLE
126 binary digits
PRECISION
FLOAT 126 binary digits

Data types Description Storage(Maximum)


CHAR data type used to store character data within predefined
CHAR 32767 bytes
length.
CHARACTER data type same as CHAR type, is this another
CHARACTER 32767 bytes
name of CHAR type.
VARCHAR2 data type used to store variable strings data within
predefined length.
VARCHAR2 Subtypes : Following sub type defines same length
value.
VARCHAR2 32767 bytes
Sub Data types Description
STRING
VARCHAR We can access this data type.

NCHAR data type used to store national character datawithin


NCHAR 32767 bytes
predefined length.
NVARCHAR2 data type used to store Unicode string data within
NVARCHAR2 32767 bytes
predefined length.
The RAW data type used to store binary data such as images,
RAW 32767 bytes
graphics etc.

5
Zenex Vision Degree College DBMS –BCA- SEM-II

LONG data type used to store variable string data within predefined
LONG length, This data type used for backward compatibility. Please use 32760 bytes
LONG data to the CLOB type.
LONG RAW data type same as LONG type used to store variable
string data within predefined length, This data type used for
LONG RAW 32760 bytes
backward compatibility.
Use LONG RAW data type for storing BLOB type data.

Boolean Data types


Boolean Data types stores logical values either TRUE or FALSE. Let's see Boolean data types in PL/SQL:

Data types Description

Boolean data type stores logical values. Boolean data types don’t take any parameters.
Boolean data type store either TRUE or FALSE. Also store NULL, Oracle treats NULL
Boolean
as an unassigned boolean variable.
You can not fetch boolean column value from another table.

Date/Time Data types

Date/time variable can holds value, we can say date/time data type. PL/SQL automatically converts character value in to d

Data types Description Range


DATE data type stores valid date-time format with fixed length. Starting Jan 1, 4712 BC to
DATE
date from Jan 1, 4712 BC to Dec 31, 9999 AD. Dec 31, 9999 AD
LOB types
LOB data types used to store large objects such as image, video, graphics, text or audio. Maximum size is up to
4 Gigabytes. Following are the LOB data types in PL/SQL:

Data types Description Storage(Maximum)

Size: up to 4GB (232 - 1


BFILE data type is used to store large binary objects into Operating
BFILE bytes)
System file.

BLOB data type is same as BFILE data type used to store Size: 8 TB to 128 TB
BLOB
unstructured binary object into Operating System file

5
Zenex Vision Degree College DBMS –BCA- SEM-II

CLOB data type is used to store large blocks of character data into Size: 8 TB to 128 TB
CLOB
Database.

Unknown Column types


PL/SQL this data type is used when column type is not know.

Data types Description

This data type is used to store value unknown data type column in a table. Column is
identified by %type data type.
Eg. emp.eno%type
%Type
emp name is table,
eno is a unknown data type column and
%Type is data type to hold the value.

This data type is used to store values unknown data type in all columns in a table. All
columns are identified by %RowType datatype.
%RowType Eg. emp%rowtype
emp name is table,
all column type is %rowtype.

User-Defined Subtypes

PL/SQL gives you the control to create your own sub data type that are inherit from predefined base type. Sub
types can increase reliability and provide compatibility with ANSI/ISO type. Several predefined subtypes are in
STANDARD package.

PL/SQL Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulation. PL/SQL
language is rich in built-in operators and provides the following types of operators −

 Arithmetic operators
 Relational operators
 Comparison operators
 Logical operators

 String operators

5
Zenex Vision Degree College DBMS –BCA- SEM-II

Here, we will understand the arithmetic, relational, comparison and logical operators one by one. The String
operators will be discussed in a later chapter − PL/SQL - Strings.

Arithmetic Operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us assume variable A holds 10
and variable Bholds 5, then −

Show Examples

Operator Description Example

+ Adds two operands A + B will give 15

- Subtracts second operand from the first A - B will give 5

* Multiplies both operands A * B will give 50

/ Divides numerator by de-numerator A / B will give 2

** Exponentiation operator, raises one operand to A ** B will give


the power of other 100000

Relational Operators
Relational operators compare two expressions or values and return a Boolean result. Following table shows all the
relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, (A = B) is


=
if yes then condition becomes true. not true.

!=

<> Checks if the values of two operands are equal or not, (A != B) is


if values are not equal then condition becomes true. true.
~=

5
Zenex Vision Degree College DBMS –BCA- SEM-II

Checks if the value of left operand is greater than the (A > B) is


> value of right operand, if yes then condition not true.
becomes true.

Checks if the value of left operand is less than the (A < B) is


< value of right operand, if yes then condition becomes true.
true.

Checks if the value of left operand is greater than or (A >= B) is


>= equal to the value of right operand, if yes then not true.
condition becomes true.

Checks if the value of left operand is less than or (A <= B) is


<= equal to the value of right operand, if yes then true
condition becomes true.

Comparison Operators
Comparison operators are used for comparing one expression to another. The result is always either TRUE,
FALSE or NULL.

Show Examples

Operator Description Example

The LIKE operator compares a If 'Zara Ali' like 'Z% A_i'


character, string, or CLOB value to a returns a Boolean true,
LIKE pattern and returns TRUE if the value whereas, 'Nuha Ali' like
matches the pattern and FALSE if it 'Z% A_i' returns a
does not. Boolean false.

If x = 10 then, x between
The BETWEEN operator tests
5 and 20 returns true, x
whether a value lies in a specified
BETWEEN between 5 and 10 returns
range. x BETWEEN a AND b means
true, but x between 11 and
that x >= a and x <= b.
20 returns false.

If x = 'm' then, x in ('a',


The IN operator tests set membership.
'b', 'c') returns Boolean
IN x IN (set) means that x is equal to any
false but x in ('m', 'n', 'o')
member of set.
returns Boolean true.

The IS NULL operator returns the If x = 'm', then 'x is null'


IS NULL BOOLEAN value TRUE if its returns Boolean false.
operand is NULL or FALSE if it is
not NULL. Comparisons involving

5
Zenex Vision Degree College DBMS –BCA- SEM-II

NULL values always yield NULL.

Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators work on Boolean
operands and produce Boolean results. Let us assume variable A holds true and variable B holds false, then −

Show Examples

Operator Description Examples

Called the logical AND operator. If both the (A and B) is


and
operands are true then condition becomes true. false.

Called the logical OR Operator. If any of the (A or B) is


or two operands is true then condition becomes true.
true.

Called the logical NOT Operator. Used to reverse not (A and


the logical state of its operand. If a condition is true B) is true.
not
then Logical NOT operator will make it false.

PL/SQL Operator Precedence


Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.

The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN,

IN. Show Examples

5
Zenex Vision Degree College DBMS –BCA- SEM-II

Operator Operation

** exponentiation

+, - identity, negation

*, / multiplication, division

+, -, || addition, subtraction, concatenation

comparison

NOT logical negation

AND conjunction

OR inclusion

Control Structures
PL/SQL Control Structures are used to control flow of execution. PL/SQL provides different kinds of statements
to provide such type of procedural capabilities. These statements are almost same as that of provided by other
languages.
The flow of control statements can be classified into the following categories:

 Conditional Control (or) Decision making Control Statements


 Iterative Control (or) Repetitive (or) Looping Control Statements

Conditional control statements: Sequence of statements can be executed based on some condition is called
conditional control statements
There are three forms of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-ELSIF.

1. if then:-
Syntax: if<condition> then
statements;
end if;

5
Zenex Vision Degree College DBMS –BCA- SEM-II

working : The sequence of statements is executed only if the condition is TRUE. If the condition is FALSE or
NULL, the IF statement does nothing. In either case, control passes to the next statement.

2. if then else:-
syntax: if<condition>then
statements;
else
statements;
end if;

working: If the condition is true then the statements associated with the if block will be executed otherwise the
statements associated with else block will be executed.

3. if then elseif:-

syntax: if<condition>then
statements;
elsif<condition>then
statements;
elsif<condition>then
statements
end if;
working: It allows you to choose between several alternatives. If the condition is true it executes sequence of
statements under if block otherwise it will check the next condition and so on…

Iterative control statements

The sequence of statements can be executed any number of times using loops.Loops in PL/SQL can be broadly
classified as

1. Simple loop
2. While loop
3. For loop
1. Simple loop:

A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates.
An EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of
iterations. When the EXIT condition is satisfied the process exits from the loop.

Syntax :
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
These are the important steps to be followed while using Simple Loop.
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement without WHEN condition,
the statements in the loop is executed only once.

6
Zenex Vision Degree College DBMS –BCA- SEM-II

2) While Loop:
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition
is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
Syntax :

WHILE <condition>
LOOP statements;
END LOOP;

Important steps to follow when executing a while loop:


1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not done oftenly.

3) FOR Loop:
A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between
the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter
reaches the value of the end integer.
Syntax :
FOR counter IN val1..val2
LOOP statements;
END LOOP;

 val1 - Start integer value.


 val2 - End integer value.

Important steps to follow when executing a while loop:


1) The counter variable is implicitly declared in the declaration section, so it's not necessary to declareit explicitly.
2) The counter variable is incremented by 1 and does not need to be incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but it's not done often.

Cursors

Oracle creates a memory area, known as the context area, for processing an SQL statement, which contains all the
information needed for processing the statement; for example, the number of rows processed, etc.

A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A cursor holds the
rows (one or more) returned by a SQL statement. The set of rows the cursor holds is referred to as the active set.

There are two types of cursors −

 Implicit cursors
 Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no
explicit cursor for the statement. Programmers cannot control the implicit cursors and the information in it. The
6
Zenex Vision Degree College DBMS –BCA- SEM-II

Implicit cursors do not have any declarations i.e opening, fetching, closing statements. The implicit cursors will fetch
the records from database to a host variable by using “into” keyword.
The following table provides the description of the most used attributes –

S.No Attribute & Description

%FOUND

1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected


one or more rows or a SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.

%NOTFOUND

The logical opposite of %FOUND. It returns TRUE if an INSERT,


2
UPDATE, or DELETE statement affected no rows, or a SELECT INTO
statement returned no rows. Otherwise, it returns FALSE.

%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL statement.

%ROWCOUNT

4 Returns the number of rows affected by an INSERT, UPDATE, or


DELETE statement, or returned by a SELECT INTO statement.

Ex:

Declare
rec emp%rowtype;
begin
select *into rec from emp where empno:=&empno;
dbms_output.put_line(rec.empno||‟ „ rec.ename||‟ „ ||rec.sal);
end;

Explicit Cursors:
The cursor which is used to hold (store) multiple records at a time is called explicit.

6
Zenex Vision Degree College DBMS –BCA- SEM-II

These cursors are manipulated by user explicitly in the PL/SQL code block. The explicit cursors follow the below
declarations

 Declaring the cursor for initializing the memory


 Opening the cursor for allocating the memory
 Fetching the cursor for retrieving the data
 Closing the cursor to release the allocated memory

Cursor processing commands:-


Declaring the Cursor
Declaring the cursor defines the cursor with a name and the associated SELECT statement.

For example −

CURSOR c IS
Opening the Cursor
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned by the
SQL statement into it. For example, we will open the above defined cursor as follows −

Fetching the Cursor


OPEN c;
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the above-opened
cursor as follows −
Closing the Cursor
FETCH c INTO c_id, c_name, c_addr;
Closing the cursor means releasing the allocated memory. For example, we will close the above-opened cursor as
follows −

Eg:
CLOSE c;
Declare
rec emp%rowtype;

6
Zenex Vision Degree College DBMS –BCA- SEM-II

cursor c1 is select * from emp;


begin
open c1;
loop
fetch c1 into rec;
exit when c1%not found;
dbms_output.put_line(rec.empno||‟ „ rec.ename||‟ „ ||rec.sal);
end loop;
close c1;
end;

Example PL/SQL programs

Q: Print Hello World in Pl/Sql

Begin
dbms_output.put_line ('Hello World');
end;

Q: Write a PL/SQL code block to find sum of numbers.

declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('Sum of ' || a || ' and ' || b || ' is ' || c);

Q: Write a PL/SQL code block to find prime number or not

DECLARE
no NUMBER (3) := &no;
a NUMBER (4);
b NUMBER (2);

6
Zenex Vision Degree College DBMS –BCA- SEM-II

BEGIN

FOR i IN 2..no - 1
LOOP
a := no MOD i;
IF a = 0
THEN
GOTO out;
END IF;
END LOOP;
<>
IF a = 1
THEN
DBMS_OUTPUT.PUT_LINE (no || ' is a prime number');
ELSE
DBMS_OUTPUT.PUT_LINE (no || ' is not a prime number');
END IF;
END;

Q: Write a PL/SQL code block to find factorial of a number.

Solution:

declare
n number;
i number;
f number:=1;
begin
n:=&n;
for i in
1..n loop
f:=f*i;
end loop;
dbms_output.put_line(n||'! = '||f);
end;
Output:

Enter value for n: 5


old 6: n:=&n;
new 6: n:=5;
5! = 120
PL/SQL procedure successfully completed.

6
Zenex Vision Degree College DBMS –BCA- SEM-II

Q: Write a PL/SQL code block to find reverse of a number.

Solution:

declare
N number;
S NUMBER := 0;
R NUMBER;
K number;
begin
N := &N;
K := N;
loop
exit WHEN N = 0;
S := S * 10;
R := MOD(N,10);
S := S + R;
N := TRUNC(N/10);
end loop;
dbms_output.put_line('THE REVERSED DIGITS OF '||K||' = '||
S); end;
Output:

Enter value for n: 4567


old 7: N := &N;
new 7: N := 4567;
THE REVERSED DIGITS OF 4567 = 7654
PL/SQL procedure successfully completed.
Q: Write a PL/SQL code block to find greatest of three numbers.

Solution:

declare
a number := &a;
b number := &b;
c number := &c;
begin
if a>b and a>c then
dbms_output.put_line(a||' is greatest.');
elsif b>a and b>c then
dbms_output.put_line(b||' is greatest.');
else
dbms_output.put_line(c||' is greatest.');
end if;
end;
Output:

Enter value for a: 6


old 2: a number :=
&a; new 2: a
number := 6; Enter
value for b: 3 old 3: b
number := &b; new 3:
b number := 3; Enter

6
Zenex Vision Degree College DBMS –BCA- SEM-II

value for c: 4

6
Zenex Vision Degree College DBMS –BCA- SEM-II

old 4: c number :=
&c; new 4: c number
:= 4;
6 is greatest.
PL/SQL procedure successfully completed.
Q: Write a PL/SQL code block to generate Fibonacci series.

Solution:

declare
a number:= 0 ;
b number:= 1;
c number;
begin
dbms_output.put(a||' '||b||' ');
for i in 3..10 loop
c := a + b;
dbms_output.put(c||' ');
a := b;
b := c;
end loop;
dbms_output.put_line(' ');
end;
Output:

0 1 1 2 3 5 8 13 21 34
PL/SQL procedure successfully completed.
Q: Write a PL/SQL code block to find sum of digits of a number.

Solution:

declare
N number ;
S number:=0;
R number;
begin
N:=&N;
WHILE N<>0 LOOP
R := MOD(N,10);
S := S + R;
N := TRUNC(N/10);
end loop;
dbms_output.put_line('THE SUM OF THE DIGITS = '||S);
end;
Output:

Enter value for n: 535


old 6: N:=&N;
new 6: N:=535;
THE SUM OF THE DIGITS = 13
PL/SQL procedure successfully completed.

6
DATA STRUCTURES
ZENEX DEGREE COLLEGE,

Data Structures
UNIT –
I

INTRODUCTION TO DATA STRUCTURE: Definition, Data Types, Abstract Data


Types (ADT), classification of data structure - primitive & non-primitive data
structures, Linear and Non-linear data structures
ARRAYS: Definition, one dimensional array, two dimensional arrays, Applications,
pointers.
LINKED LIST: Definition, linked list ADT, single linked list, double linked list,
circular linked list, comparison of linked list with Arrays.

UNIT – II

STACKS: Definition, Stack as an ADT & Operations on stack, Applications of stack,


Representation of stack.
QUEUES: Definition, Queue as an ADT & Operations on Queue, Application of
Queues, Representation of Queues, Various Queue Structures: circular Queue,
DEQueue.

UNIT – III

TREES: Definition, Basic Tree Terminology. Binary Tree – Definition, Properties


ofBinary Trees, Types of Binary Trees, Representation of Binary Tree, Binary Tree
Traversals. Binary Search Tree (BST) – Definition, Operations on a Binary
Search Tree, Examples ofBST.
UNIT -
IV

GRAPHS: Definition, Basic Graph Terminology, Representation of Graphs, Graph Traversal


– DFS and BFS. Topological sort, Shortest Path problem, Minimum Spanning Tree.

UNIT – V

SORTING: Definition, Sorting methods - Bubble Sort, Selection Sort, Quick Sort,
InsertionSort, Merge Sort.
SEARCHING: Definition, searching methods - Linear or Sequential Search, Binary Search.

1
ZENEX DEGREE COLLEGE,

UNIT I
Concept of Abstract Data Types (ADTs)
1. Define
Data may be data structures.
organized List various
in many different ways. Thetypes
logicalof(or)
data structures.
mathematical model of a
(OR) Write short notes on Primitive and Non-primitive data
particular organization of a data is called data structure. It is a collection of values and
possible operations.
Structural representation of data items, storage & retrieval operations efficiently.

Primitive Data Structures


⬧ Primitive Data Structures are the basic data structures that directly operate
upon the machine instructions.
⬧ Primitive data structures have different representations on different computers.
⬧ Integers, Floating point numbers, Character constants, String constants and Pointers
come under this category.
⬧ These data types are available in most programming languages as built in type.
o Integer: It is a data type which allows all values without fraction part. We can use
it for whole numbers.
o Float : It is a data type which use for storing fractional numbers.
o Character: It is a data type which is used for character values.
o Pointer : Pointer is a variable which holds memory address of another variable.

Non – Primitive data structures: Non-primitive data structures are more


shopisticated data structures.
 These are derived from primitive data structures. But extending the size and ranges
of basic data type
 They focus on grouping same or different data items with relationship between each

2
ZENEX DEGREE COLLEGE,

data item.
 Arrays, Lists and Files come under this category.
 Array: An array is a collection of memory locations which can share same data
name and same data type values.
 List: An order set containing variable number of elements is called as lists.
o The list is a sequential data structure.
o Lists are a way to store many different values under a single variable.
o Every item in this list is numbered with an index.
 File: A file is a collection of logically releated inforation. It can be viewed as
large list of records consisting of various fields.
 A Non- primitive data type is further divided into linear and Non- linear
data strucutre.
⬧ Linera data stucture: A data structure is said to be linear if its elements form a
sequence or a linear list. Example: array, stacks, queues and linked lists come under
this category.
⬧ Non- Linear data strucutres: A data structure is said to be non linear if its elements
form a hierarchical classification where, data items appear at various levels.Trees and
Graphs are widely used non-linear data structures.

Write a detail note on 1. ADT 2.Composite types 3. Primitive types

Data Type: Data type defines what type of value to stored on a variable.(or)A data type
defines a set of values and the allowable operations on those values. Different data types
include:
1. Abstract data types (ADT )
2. Composite types
3. Primitive types
Abstract data types (ADT ) : Abstract data types are mathematical models ofa
set of data values or information that share similar behaviors. Abstract data types
are used in algorithms and also data items.(OR)
ADT is a user defined data type which encapsulates a range of data values and
their functions. (OR)

An abstract data type is a definition of new type, describes its properties and
operations.
Ex: ―Stack‖ is a ADT which contains push( ), pop( ) operations.
―Linked List‖ is a ADT which contains insert( ), delete( ) operations etc.
In an ADT, we encapsulate the data and the operations on data and we hide
them from the user.An abstract data type consists of
i) Declaration of data
ii) Declaration of operations
Advantages:
⬧ Code is easier to understand.

3
ZENEX DEGREE COLLEGE,
⬧ Implementations of ADTs can be changed without requiring changes to

4
ZENEX DEGREE COLLEGE,

the program that uses the ADTs.


⬧ ADTs can be reused in future programs.
Composite types: Composite data type is any data type which can be
constructed in a program using the programming languages like primitive data
types and other data types.
Example : Structures, unions in ‗c‘.
struct Account
{
int account_number;
char first_name;
char last_name;
float balance;
};
Primitive types:
Primitive types are data types provided by a programming language. Primitive
types are also known as built-in types or basic types.
primitive types may include:
1. Character (character, char);
2. Integer (integer, int, short, long, byte) with a variety of precisions;
3. Floating-point number (float, double, real, double precision);
4. Boolean having the values true and false.
Basic primitive types :
SIZE NAME SIGNED INTEGER UNSIGNED
RANGE INTEGER RANGE
8 bits Byte -128 to + 127 0 to 255
16 bits Integer -32,768 to +32,767 0 to 65,535
-2,147,483,648
Double to
32 bits Long +2,147,483,648 0 to 4,294,967,295
integer
64 bits Long(JAV -9,223,372,036,854,775,808 0 to
A) to 18,446,744,073,709,551,
+9,223,372,036,854,775,808 615

Integer numbers
An integer number can hold a whole number, but no fraction. Integers may be
either signed (allowing Negative values) or unsigned (non negative values only).

Floating-point numbers
A floating-point number represents a real number that may have a fractional
part. These numbers are stored internally in scientific notation, they also called
decimal number. Floating point number contains integer, decimal point(.) and
exponent notation(‗e‘).
Examples of floating-point literals are: 20.0005 , 99.9 , −5000.12 , 6.02e23
Boolean: A boolean type is a single-bit type that can be either true (1) or
false (0).
Characters and strings: A character type (typically called "char") may contain

5
ZENEX DEGREE COLLEGE,

a single letter, digit, punctuation mark, or control character.Characters may be


combined into strings. The string data can include numbers and other numerical
symbols but will be treated as text.
Examples: ‘G‘ ‗M‘, "gminformatics" ,…

Discuss about linear and Non linear data structures.

Linear data structures:


⬧ A data structures is said to be linear, if its elements are connected in linear
fashion by means of logically or in sequence memory locations.
⬧ A Linear data structure is a sequential representation of several data items
with one starting point and one ending point. That is a linear data structure
will have only one starting point and only one ending point.

⬧ There are two ways to represent a linear data structure in memory,


o Static memory allocation
o Dynamic memory allocation
⬧ The possible operations on the linear data structure are Traversal,
Insertion, Deletion, Sorting and Merging.
⬧ Example of linear data structure One Dimensional Array, Linear Linked List,
Stack, Linear Queue.
⬧ Array: An array is a collection of memory locations which can share same
data name and same data type values.
⬧ Stack: Stack is a data structure in which insertion and deletion operations
on performed at one end only.
o The Insertion operation is refered to as ‗PUSH‘ and deletion oepration
is referred to as ‗POP‘ Operation.
o Stack is also called as Last in Fist Out( LIFO) data structure.
⬧ Queue: The data structure which permits the insertion at one end and
deletion at another end, known as Queue.
o End at which deletion is occurs is known as FRONT end and another
end at which insertion occurs is known as REAR end.
o Queue is also called as First in First out data structure.
Non linear data structures:
⬧ Non linear data structures are those data structure in which data items are
not arranged in a sequence.
⬧ A non-linear data structure is a non-sequential representation of several
data items with several starting points and several ending points or no
definite starting and ending points.
⬧ Example of non linear data structure are Hierarchical Structures, Circular
Structures, Topographical Structures tree and Graph.

6
ZENEX DEGREE COLLEGE,

Topographical Structures:

Diplom

Circular structure:

⬧ Tree: a tree can be defined as finite set of data items(nodes) in which data
items are arranged in branches and sub branches according to requirement.
⬧ Trees consist of nodes connected by edge, the node presented by circle and
edge lives connecting to circle.
⬧ Graph: Graph is a collection of nodes (information) and connecting edges(
Logical relation) between nodes.
⬧ A tree can be viewed as a restricted graph.
⬧ Graphs have many types.
o Un- directed graph
o Directed graph
o Mixed graph
o Multi graph
o Simple graph
o Null graph
o Weighted graph

Linear
Diference Data structure
between linear and Non linearNon Linear
data data structure
structures:
Every item is related to the previous Every item is attached with many
and time other items.

7
ZENEX DEGREE COLLEGE,

Data is arrange is linear sequence Data is not arranged in sequence


Data items can be traversed in a Data cannot be traversed in single run.
single run.
Eg. Array, stacks, linked list, queue Eg.tree, graph
Implementation is easy Implementation is difficult.

8
ZENEX DEGREE COLLEGE,

Arrays
Definition:

An array is a finite, ordered and collection of homogeneous data elements. An


array is finite because it contains only a limited number of elements, orderedas
all the elements are stored one by one in contiguous locations of the computer
memory in a linear order. As homogeneous all the elements of an array are of the
same data type.
Basic Terminology:
Size: The number of elements in an array is called the size or length of the array.
Type: The type of an array represents the kind of data type .
Base: The base of an array is the address of the memory location where the first
element of the array is located.
Element − Each item stored in an array is called an element.
Index: All the elements in an array can be referenced by a subscript like A[i],
this subscript is known as index. The index value is always an integer value.
Range of Indices: Indices of arrays elements may range from a lower bound to
an upper bound called boundaries of an array.
Word: Word ‗w’ denotes the size of an element i.e., the amount memory that is
required to store an element of the array.

One-Dimensional arrays and their address mapping and operations


Definition:An array is a finite, ordered and collection of homogeneous data
elements. An array is finite because it contains only a limited number of
elements, ordered as all the elements are stored one by one in
contiguous/consecutive locations of the computer memory in a linear order. As
homogeneous all the elements of an array are of the same data type.

One-Dimensional Array:If only one subtype/index is required to refer an


element in an array, then the array is called as ―One-Dimensional Array‖.

Memory Allocation:All the indexed variables of an array are allocated


contiguous memory locations in computer‘s memory. So memoryrepresentation
of an array is simple. Suppose, we have an array with
n indexed variables, let the memory location of the first element is M.
If each element requires one word, then the location of any element in
the array can be calculated by using the following formula.Address
(A[i]) =M+(i x w)

Physical Representation

Eg: Let M=4560 and w=1,calculate the address of A[0], A[2], A[7]

Address (A[0]) = 4560+(0)x1 = 4560

9
ZENEX DEGREE COLLEGE,

Address (A[2]) = 4560 +(2)x1 = 4562

Address (A[7]) = 4560 +(7)x1 = 4567

Operations: Various operations that can be performed on an array are like


Traversing, Sorting, Searching, Insertion, Deletion and Merging.

Following operations can be performed on arrays:

Traversing: It is used to access each data item exactly once so that it can be
processed.
Searching: It is used to find out the location of the data item if it exists in the
given collection of data items.
Insertion: It is used to add a new data item in the given collection of data
items.
Deletion: It is used to delete an existing data item from the given collection of
data items.
Sorting: It is used to arrange the data items in some order i.e. in ascending or
descending order in case of numerical data and in dictionary order in case of
alphanumeric data.
Merging: It is used to combine the data items of two sorted files into single file
in the sorted.
Multi-Dimensional arrays and their address mapping and operations
Definition:An array is a finite, ordered and collection of homogeneous data
elements. An array is finite because it contains only a limited number of
elements, ordered as all the elements are stored one by one in contiguous
locations of the computer memory in a linear order. As homogeneous all the
elements of an array are of the same data type.

Multi-Dimensional Array:If elements are represented using more than one


index/subscript, then the array is called as ―Multi-Dimensional Array‖. Two
dimensional arrays are a collection of homogeneous elements in which elements
are ordered in rows and columns.

Eg: Consider an array of size mxn, here m is the no.of rows and n is the no.of
columns as follows.

a11 a12 a13............a1n


a21 a22 a23............a2n mXn
. . . ……………………

1
ZENEX DEGREE COLLEGE,

Memory Representation: Like one-dimensional arrays, two-dimensional arrays


are also stored in contiguous memory locations. There are two conventions of
storing two-dimensional array elements in the memory.

1. Row-Major Order

2. Column-Major Order

Row-Major Order:The elements of a two-dimensional array are stored in row- by-


row basis, that is all the elements in the first row, then in the second row and so
on.

Column-Major Order:The elements of a two-dimensional array are stored in


column-by-column basis, that is all the elements in the first column are stored
in their order of rows, then in the second column and so on.
Eg:
a11 a12 a13
a21 a22 a23
a31 a32 a33
3X3

Memory Representation

Referencing an element: To refer an element in a two-dimensional structure,


we need two index values one for row another for column. The indexing formula
of row-major order is different from columnmajor order.Let us assume that we
have an array with mxn elements.

Row-Major Order:

Address(aij) = (i-1)xn+j

Eg: Address(a32) = ((3-1)x3)+2 = 2x3+2 = 8

If the base address is M, then the above formula can be modified as follows.

1
ZENEX DEGREE COLLEGE,

Address(aij) = M+(i-1)xn+j-1

Eg: Address(a32) = 4560+((3-1)x3)+2-1

= 4560+2x3+2-1

=4560+6+2-1 = 4567

Column-Major Order:

Address(aij) = (j-1)xm+j

Eg: Address(a32) = ((2-1)x3)+2 = 2x3+2 = 6

If the base address is M, then the above formula can be modified as follows.

Address(aij) = M+(j-1)xm+i-1

Eg: Address(a32) = 4560+((2-1)x3)+3-1

= 4560+3+3-1

=4560+3+2 = 4565

Sparse Matrix and representation of Sparse Matrix

A sparse matrix is a two – dimensional array where the majority of the elements have
the value null.

Input : An array a with two- Another array spm with two multiplied by 3.`

Output : Representation of Sparse Matrix in a Triplet Form.

SparseMatrix:Two columns mxn . There may be situation in ins Non-Zero values. Such
matrix is non-zero values, that is majority of values non-zero values. So, to represent those
6 values, we are we can represent the sparse matrix by using Triplet - dimensions containing
elements, most of the elements are zeros two-dimensions whose size is equal to no.of non-
dimensional array.

The above matrix contains 5 rows and 6 columns. Then the total number of
elements are 5x6=30. If each element requires 4 Bytes of memory, then we need
totally 120 Bytes of memory. But if we observe the matrix, it has very few non-zero
values, that is majority of values are zeros. We have only 6 non-zero

1
ZENEX DEGREE COLLEGE,

values. So, to represent those 6 values, we are wasting 120-(6x4) = 120-24 = 96


Bytes of memory. (6x4) = 120-24 = 96 Bytes of memory.

An array a with two-dimensions containing elements, most of the elements are


zeros Another array spm with two-dimensions whose size is equal to no.of non-
null values multiplied by 3. Representation of Sparse Matrix in a Triplet Form.

Sparse matrices are used by scientists and engineers when solving partial
differential equations. For example, a measurement of a matrix's sparsity can
be useful when developing theories about the connectivity of computer
networks. When using large sparse matrices in a computer program, it is
important to optimize the data structures and algorithms to take advantage
of the fact that most of the values will be zero.

1
ZENEX DEGREE COLLEGE,

Discuss about the list implementation concepts.

Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two
parts.Each node consists of its own data and the address of the next node and
forms a chain.Linked Lists are used to create trees and graphs.

Advantages of Linked Lists


👉 They are a dynamic in nature which allocates the memory when
required.
👉 Insertion and deletion operations can be easily implemented.
👉 Stacks and queues can be easily executed.
👉 Linked List reduces the access time.
Disadvantages of Linked Lists
👉 The memory is wasted as pointers require extra memory for storage.
👉 No element can be accessed randomly.
👉 it has to access each node sequentially.
👉 Reverse Traversing is difficult in linked list.

Applications of Linked Lists


 Memory management: linked list are useful in managing memory
as dynamic i.e., DMA.
 Polynomial manipulations: the operations on polynomial such as
addition, subtraction,multiplication etc are easily implemented using
linked lists.
 Insertions and deletions in graphs of data: the insertions and deletions
are efficiently performed when linked lists are used to maintain the group of
data.
 Linked lists are used to implement stacks, queues, graphs, etc.
 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don‘t need to know the size in advance.

1
ZENEX DEGREE COLLEGE,

Types of Linked Lists

Singly Linked List : Singly linked lists contain nodes which have a data part as
well as an address part i.e. next, which points to the next node in sequenceof
nodes. The operations we can perform on singly linked lists are insertion,
deletion and traversal.

Doubly Linked List : In a doubly linked list, each node contains two links the first link points to the previ
in the sequence.

Circular Linked List : In the circular linked list the last node of the list contains
the address of the first node and forms a circular chain.

1
ZENEX DEGREE COLLEGE,

Linked List & Single Linked Linear List

A linked list is an ordered collection of finite, homogeneous data elements called


nodes. Unlike arrays, linked lists are dynamic structures as nodes are created
whenever we require. The amount of memory required can be variedduring its use.
In Linked Lists, the adjacency is maintained by using links or pointers. A link or
pointer is the address of the subsequent(next/previous) element in the list. So, we
need to maintain both data and link in a node. Thus,a node consists of two parts
Data and Link.Data part of a node holds the user'sdata and Link part of the node
holds the address value of its next/previous node in the list. Link

DATA Link to the next node

Single Linked List: In single linked list, each node contains only one link which
points to the next node in the list. We maintain a pointer called Headptr to
point the very first node of the list.

In the above example, we have five nodes from N1 to N5. The first node is
called as Head Node and last node is called as Tail Node. First node points to
second, second points to third and so on. Tail Node always points to null which
indicates there no more node in the list. In single-linked list, we can travel only in
direction that is from Head Node to Tail Node. We can move only to the next
node not to the previous node of the list. That is why it is called as one way list.

Operations:

addNewNode (data): This operation adds a new node to the list with the given
data.

delete (index): This operation deletes an existing node from the list at given
index position.

size(): This operation gives the size i.e., how many nodes are there in the list.

insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.

traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.

1
ZENEX DEGREE COLLEGE,

Define linked list. Explain how to insert and delete an element at


the beginnning of the list.

Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two parts.

Each node consists of its own data and the address of the next node and forms
a chain.Linked Lists are used to create trees and graphs.

Insertion: : Insertion is used to add a new data item. A node can be inserted in various positions.
Inserting at the front ( as a first element)
Inserting at end ( as a last element)
Inserting at any position.
Steps for inserting an element in the beginning of a list
Create a new node
Make the next part of new node point to the first node
Make the START pointer point to new node
Algorithm
new_nodenext=START; START =new_node;

1
ZENEX DEGREE COLLEGE,

Steps for inserting an element in the end


1. Create a new node
2. Make the next of new node point to NULL
3. Make the previous node point to new node.
Algorithm for Insert a node at the end of a single linked list:

while(pnext!=NULL)
{
p=pnext;
}
pnext=new_node; new_nodenext=NULL;

Steps for inserting an element in the middle


Create a new node
Make the next part of new node point to the next of previous node
Make the previous node point to new node
Algorithm for Insert a node at the middle of a single linked list:

while(p!=insert_position)
{
P=pnext;
}
store_next=pnext;
pnext=new_node; new_nodenext=store_next;

1
ZENEX DEGREE COLLEGE,

Deleting a node from a list: It is used to delete an existing data item from the
given collection of data items. There three ways to delete element.

i. Deleting from the front of the list


ii. Deleting from the end of the list
iii. Deleting from any position in the list

Steps for deleting a node in the beginning


Store the node to be deleted in a temporary pointer
Make START point to next node in the list
Delete the node pointed by temporary pointer

Steps for deleting a node from the middle / end


Store the node to be deleted in a temporary pointer
Make the previous node‘s next point to the next of the node that is being deleted
Delete the node pointed by temporary pointer

Steps for deleting a node from the middle / end


Store the node to be deleted in a temporary pointer
Make the previous node’s next point to the next of the node that is being deleted
Delete the node pointed by temporary pointer

1
ZENEX DEGREE COLLEGE,

Algorithm for deleting a node in single linked list

node *delete(node *head, char d)


{
node *p, *q;
q=head;
p=headnext;
if(qdata==d) //start node
{
head=p;
delete(q);
}
else //internal node
while(pdata!=d) Last node
{
p=pnext;
q=qnext;
}
if(pnext==NULL)
{
qnext=NULL;
delete(p);
}
else
{
qnext=p—next;
delete (p);
}
return head;
}

2
ZENEX DEGREE COLLEGE,

Discuss about Double Linked Linear List

A linked list is an ordered collection of finite, homogeneous data elements called


nodes. Unlike arrays, linked lists are dynamic structures as nodes are created
whenever we require. The amount of memory required can be variedduring its
use.

In Linked Lists, the adjacency is maintained by using links or pointers. A link or


pointer is the address of the subsequent(next/previous) element in the list.So,
we need to maintain both data and link in a node. Thus, a node consists of two
parts Data and Link. Data part of a node holds the user's data and Link part of
the node holds the address value of its next/previous node in the list.

Double Linked List:


In double linked list, each node contains two links one points to the next node
another points to the previous node in the list. We maintain a pointer called
Headptr to point the very first node of the list.

Example:

In the above example, we have four nodes from N1 to N4. The first node is
called as Head Node and last node is called as Tail Node. First node points to
second, second points to third and so on. The left link of head node and right
link of tail node points to null. It indicates that there is no previous node
tohead and no next node to tail node. In double-linked list, we can travel
ineither directions that is from Head Node to Tail Node and Tail Node to Head
Node. That is why it is called as two-way list.

Memory Organization Of A Doubly Linked List

2
ZENEX DEGREE COLLEGE,

Operations:
addNewNode (data):This operation adds a new node to the list with the given
data.
delete (index):This operation deletes an existing node from the list at given
index position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.
traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.
Define double linked list. Explain how to insert and delete an
element at the end of the list.
In double linked list, each node contains two links one points to the next node
another points to the previous node in the list. We maintain a pointer called
Headptr to point the very first node of the list.
Steps for inserting in the beginning of a doubly linked list
1. Create a new node
2. Make the next part of new node equal to START
3. Make the previous part of new node equal to NULL
4. Make the previous part of the node pointed by START to new node
5. Make START point to new node
Algorithm for insert a node at the start
new_nodenext=head;
headprev=new_node;
new_nodeprev=NULL;
head=new_node;

Steps for inserting an element in the middle of a doubly linked list


1. Create a new node
2. Make the next part of new node equal to next part of the previous node
3. Make the previous part of new node equal to previous part of next node
4. Make the next part of previous node point to new node
5. Make the previous part of next node point to new node

2
ZENEX DEGREE COLLEGE,

Algorithm for insert internal node.


while(p!=insert_position)
{
p=pnext
}
store_next=pnext
pnext=new_node;
new_nodenext=store_next;
store_nextprev=new_node;

Steps for inserting an element at the end of a doubly linked list


1. Create a new node
2. Make the next part of the new node equal to NULL
3. Make the previous part of the new node equal to TAIL
4. Make the next part of the previous node equal to new node
5. Make TAIL equal to new node
Algorithm: while(pnext!
=NULL)
{
p=pnext;
}
pnext=new_node;
new_nodeprev=p;
new_nodenext=NULL;

2
ZENEX DEGREE COLLEGE,

Deleting an element from a doubly linked list


Deleting a node from a list is as simple as changing the links. Hence deleting a
node from a list is much faster when compared to arrays. Like insertion the
deletion logic also varies depending on from where in the list we are going to
delete the node.

1. Deletion at beginnning

2. Deletion at middle

3. Deletion at end

Deletion in the beginning of a doubly linked list


1. Make the temporary pointer point to the node to be deleted
2. Make the START point to the next node of START
3. Make the previous of the next node equal to previous of the node to be deleted
4. Delete the node pointed to by temporary pointer.

Algorithm:

p=head;

head=headnext;

headprev=NULL;

delete(p);

Deletion in the middle of a doubly linked list


1. Make the temporary pointer point to the node to be deleted
2. Make the next part of the previous node equal to next of the node to be deleted
3. Make the previous part of the next node equal to previous part of the node to be
deleted
4. Delete the node pointed to by temporary pointer
Algorithm:
While(p!=delete_position)
{

2
ZENEX DEGREE COLLEGE,

P=pnext;
}
store_next=pnext;
store_prev=pprev;
store_nextprev=store_prev;
store_prevnext=store_next;
delete(p);

Deletion at the end of a doubly linked list


Make the temporary pointer point to the node to be deleted

Make the next part of the previous node equal to next of the node to be deleted

Make the TAIL equal to the previous part of the node to be deleted

Delete the node pointed to by temporary pointer.

Algorithm: store_prev=pprev; store_prevnext=NULL; delete(p);

2
ZENEX DEGREE COLLEGE,

Write a detiled note on Circular Linked List .

A linked list is an ordered collection of finite, homogeneous data elements called


nodes.Unlike arrays, linked lists are dynamic structures as nodes are created
whenever we require. The amount of memory required can be variedduring its use.
In Linked Lists, the adjacency is maintained by using links or pointers. A link or
pointer is the address of the subsequent(next) element in thelist. So, we need to
maintain both data and link in a node. Thus, a node consists of two parts Data
and Link. Data part of a node holds the user's dataand Link part of the node
holds the address value of its next/previous node inthe list.

CircularLinked List: A linked list where the last node points the header node
is called the ‗Circular Linked List‘. A circular list doesn't have definite head and
definite tail nodes. Any Node in the list can be chosen as Head and node before
that as Tail. If there are more than one Node in the list, then every Node will
have next Node. If there is only one Node in the list that itself is the head and
tail. The tail Node in the circular list points to the head Node.

Operations:
addNewNode (data):This operation adds a new node to the list with the given data.
delete (index):This operation deletes an existing node from the list at given index
position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given index
position with a givendata value.
traversal():This operation gathers data from each node in the list starting from head to
tail node and displays the data.

2
ZENEX DEGREE COLLEGE,

Differences between single linked list and double linked list

SINGLE LINKED LIST DOUBLE LINKED LIST

1. In SLL the list will be traversed in 1. In DLL the list will be traversed
only one way i.e., in forward in two ways either in forward (or)
direction. Backward directions.

2. In SLL the node contains only one 2. In DLL each node contains two Link
link field. fields.

3. The conceptual view (a logical 3. The conceptual view (a logical


organisation) of SLL is: organization) of a DLL is:

4. Every node contains the address 4. Every node contains the address of
of next node. next node as well as the address of the
previous node.

5. The node structure of DLL is as


5. The node structure SLL is as follows: follows

6. In DLL the first node address is


6. In SLL the first node address is
stored in ―left end‖ and last node
stored in a special pointer variable
address is stored in ―right end‖ pointer
―START‖.
variables.

7. Three linear arrays are required to


7. Two linear arrays are required to represent a double linked list in
represent a single linked list in memory.
memory.

2
ZENEX DEGREE COLLEGE,

UNIT-II
STACKS
1. What is a Stack? Write a short notes on Stack?
A Stack is a linear list in which insertions and deletions take place at the same end. The
end through which items are added and deleted is called the Top End. The other end of the
list is called the Bottom End.
Stack data structure allows addition and deletion of items through only one end. Addition of
items onto a Stack is called ‘Push’ operation and deletion of items from a Stack is called
‘Pop’ operation. A stack is a Las-In-First-Out (LIFO) data structure. Each Stack has a definite
size called Maximum Size of the Stack. In a stack the item that is added last will be taken
out first. So this data structure is called as LIFO data structure. Stack data structures are
used when the item that is added last need to be served first. A stack can be visualized as a
vertical structure where bottom is sealed and top is opened.
Structure of Stack data structure:

Example:

2. How to represent Stack using


Arrays? Stack Representation using
Arrays ?

2
ZENEX DEGREE COLLEGE,

A Stack data structure can be represented using arrays. We perform stack operations
Push and Pop by maintaining the top value to point to the topmost element position of the
stack. Abstract Class :
AbstractDataType Stack
{ Instances
Linear list of elements: one end is called the bottom the other is the top.
Operations
isEmpty() : Return True if stack is empty, return False otherwise.
isFull() : Return True if stack is full, return False otherwise
push(x) : Add element x to the stack
pop(x) : Delete top element from stack and put it in x.
}
Operations:
push(x) : Adding items to the stack is called as Push operation. Here x is the data item that
is being added onto the stack.

pop(x) : Deleting items from the stack is called as Pop operation. Here x is the data item
that is being deleted from the stack.
isFull( ) :This function verifies whether the stack is full or not. If stack is full, it returns
true, otherwise return false.
isEmpty():
This function verifies whether the stack is empty or not. If stack is empty, it returns
true, otherwise it returns false.
Algorithm
Stack Operations: Basically, there are two operations performed on the stack.
Push: Push is the term used to insert the element on the top of stack.
Pop: Pop is the term used to delete the elements from top of the stack.
Algorithm: push(s, top, x):[This algorithm inserts the elements.]
Step: 1 [check for the stack over flow]
If (top > = max-1) then write (“stack over flow”)
Return;
Step: 2 [increment top by 1]
top top+1;
Step: 3 [insert element]
s[top] x;
Step: 4 [finished]
Return;

2
ZENEX DEGREE COLLEGE,

Algorithm pop(s, top): [this algorithm deletes the top element from the stack]
Step: 1 [check for the stack under flow]
if (top= = -1) then write (“stack underflow”)
Return;
Step: 2 [assign top element to x]
X s[top];
Step: 3 [decrement top by 1]
top top-1;
Step: 4 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = -1) then write (“stack Empty”)
Step: 2.[finished]
Return;

Algorithm: isFull(s, top):[This algorithm checks the stack is full]


Step: 1 [check for the stack is full]
If (top > = max-1) then write (“stack is Full”)
Step: 2 [finished]
Return;

3. How to represent Stack using Linked List and explain their


operations? Stack Representation using Linked List:
When using a chain (linked list) to represent a stack, we must decide which end of
the list corresponds to top of the stack. If we associate the right end of the list as top of the
stack then the additions and deletions are implemented using the list operations push ()
and pop() . If we associate the left end of the list as top of the stack then the operations
push () and pop().
We can use either single linked or double linked list to represent a stack data
structure. But it is easy to use single linked list to represent a stack data structure.

Example :

3
ZENEX DEGREE COLLEGE,

The implementation of isFull() method is not necessary because the only way to
know whether we can add an element on to the stack or not is to see whether enough
space exists to create a node of type Node. This check can be done by invoking new.
Abstraction of Stack:
Data Objects:
Node :-consisting of two parts data and address.
headptr :-always points to the address of first node in the list
next :- used to store next node address
Methods :
isEmpty():
This method verifies that the stack is empty or not. If the stack is empty it returns
true, otherwise it returns false.
push(x):
This method adds a data item x onto the stack. If the operation executed
successfully it returns true, otherwise it returns false.
pop(x):
This method pops a data item from the stack and places it in x. If the operation
executed successfully it returns true, otherwise it returns false.

Algorithms
Algorithm: push_LL (s, top, x):[This algorithm inserts the elements.]
Step: 1[Create new node ]
New=Getnew(Node);
Step: 2 [inserting Values]
New Data=Item
Step3: [palcing reference]
New link=top
Top=new
Step: 4 [top is assigns to stack head]
Stack_Headlink=top

3
ZENEX DEGREE COLLEGE,

Step:5 [Finish]
Return;
Algorithm pop_LL(s, top): [this algorithm deletes the top element from the stack]
Step: 1 [check for the stack under flow]
PTR= Stack_Headlink;
if (PTR=NULL) then write (“stack underflow”)
Return;
Step: 2 [assign top element to x]
X PTR[top]; [Display x]
Step: 3 [Assign top to next node]
top = ptr link;
Step: 4[Assign head_ptr to top]
Stack_Head=top;
Step: 5 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = null) then write (“stack Empty”)
Step: 2.[finished]
Return;

4. What are the Applications of Stack?


APPLICATIONS OF STACKS:-
1. Stacks are used in recursion process.
2. Stacks are used in conversion of infix to post fix or prefix expressions.
3. Stacks are used in evaluation of post fix or prefix expression.
4. Stacks are used in tree traversal methods (if there are implemented in recursive
methods).
5. Stacks are used DFS of a graph.
6. Stacks are used in implementing sequence of function calls (in Operating System).

5. Implementations of Stacks?
Implementation of Recursion Process:
Recursion is a process by which a function calls itself repeatedly. In the recursion
process, a function is repeated endlessly or until some specified condition has
been satisfied. Recursion is used for repetitive computations in which each
action is started in terms of a previous result.
For Example, to find factorial of 5, it can be recursively computed as follows:
5! = 5 x 4!
4! = 4 x 3!
3! = 3 x 2!
2! = 2 x 1!
1! = 1
In the same way, the factorial of n is recursively defined as,
N! = N * (N-1)! if N > 1
= 1 if N <=1

3
ZENEX DEGREE COLLEGE,

Algorithm for Factorial(N): using Recursion


1. if (N=0) or (N<=1) then
2.fact=1
3.else
4.fact=N*Factorial(N-1);
5.end if
6.return(fact)
7.stop
Algorithm for factorial with stack:
Note:Array representation of stack
1.val=N,top=0,addr=step 15
2.initialise the stack
PUSH(val,addr)
3.val=val-1,addr=step 11
4.if (val=0)then
5. fact=1
6. go to step 12
7.else
8.PUSH(val,addr)
9.go to step 3
10.end if
11. fact=val*fact
12.val=POP_PARAM(),addr=POP_ADDR()
//POP_PARAM() and POP_ADDR() are the two POP operations assumed on two
stacks PARAM and ADDR respectively.
13. goto addr
14. return (fact)
15.stop
Tower of Hanoi Problem: It is also implemented using recursion. This problem is defined
as Assume there are 3 pillars A,B,C. There are N discs of decreasing size so that no two
discs are of the same size. Initially, all the discs are stacked on one pillar in their
decreasing order of size. Let this pillar be A. The other two pillars are empty. The problem
is to move all the discs from one pillar to another using the third pillar C.
Rules:
 Only one disc may be moved at a time.
 A disc may be moved from any pillar to another pillar
 At no time can a larger disc be placed on a smaller disc.
The solution of this problem can be defined recursively as:
 Move N discs from pillar A to C through pillar B means
 Moving the first (N-1)discs from pillar A to B.
 Moving the disc from pillar A to C.
 Moving all (N-1)discs from pillar B to C.
Algorithm for Moving Discs:
N=no. of discs in the tower of Hanoi
ORG=origin(from pillar)
INT=intermediate(via pillar)
DES=destination(to pillar)
1. if N>0 then

3
ZENEX DEGREE COLLEGE,

2. Move(N-1,ORG,DES,INT)
3. ORG=DES(Move from ORG to DES)
4.Move(N-1,INT,ORG,DES)
5. End if
6.stop

6. Explain Evaluation of Arithmetic Expressions?


An Arithmetic Expression consists of operands and operators. Operands
may be variables or constants. operators are arithmetic operators(+,-,*,/,%,^).In
addition to these parentheses such as ‘( ‘and ‘ ) ‘are also used.
For example: A+B*C/D-E^F*G
Notations for Arithmetic Expressions:
There are 3 notations to represent an arithmetic expression. They are
1) INFIX NOTATION
2) PREFIX NOTATION
3) POSTFIX NOTATION
1. Infix notation: In infix notation the operator is in between 2 operands.
Syntax:
Operand operator operand
Ex: A+B,C-D,F*G etc.,
2. Prefix notation(Polish notation): In Prefix notation the operator is preceded by 2
operands. That means the operator comes before the operands. The prefix notation is
introduced by Polish mathematician Jan Lukasiewicz. So, the Prefix notation also called as
Polish notation.
Syntax:
operator operand operand
Ex: +AB,-CD,*FG etc.,
3.Postfix notation: In Postfix notation the operator is followed by 2 operands. That
means the operator comes after the operands. The postfix notation is just reverse of
prefix(Polish)notation. So, it is also called as Reverse Polish notation.
Syntax:
operand operand operator
Ex: AB+, CD-, FG* etc .,

7.CONVERSION OF AN INFIX EXPRESSION TO POSTFIX EXPRESSION?


Data objects required for the conversion are
–An operator / parentheses stack
–A Postfix expression string to store the resultant
–An infix expression string read one item at a time
Algorithm for converting infix to postfix expression:
What are possible items in an input Infix expression
Read an item from input infix expression
If item is an operand append it to postfix string
If item is “(“ push it on the stack
If the item is an operator
If the operator has higher precedence than the one already on top of the stack then push
it onto the operator stack
If the operator has lower precedence than the one already on top of the stack then
pop the operator on top of the operator stack and append it to postfix string, and

3
ZENEX DEGREE COLLEGE,

push lower precedence operator onto the stack


If item is “)” pop all operators from top of the stack one-by-one, until a “(“ is encountered
on stack and removed
If end of infix string pop the stack one-by-one and append to postfix string Convert
the following infix expression A + B * C – D / E * H into its equivalent postfix
expression.

Convert ((A – (B + C)) * D) ↑ (E + F) infix expression to postfix form:

3
ZENEX DEGREE COLLEGE,

Parenthesis Problem: In this problem we are to match the left and right parenthesis in
a character string. We observe that if we scan the input string from left to right, then each
right parenthesis is matched to the most recently seen unmatched left parenthesis. For this
we save the position of left parenthesis on a stack as they are encountered in a left-to-right
scan. When a right parenthesis is encountered then it is matched to the left parenthesis at
the top of the stack. The matched left parenthesis is deleted from the stack.

QUEUES
1. What is a Queue?
Definition:Queue is a data structure where items are added through one end and deleted
through another end. The end through which items are added is called as “Rear End” and
the end through which items are deleted is called as “Front End”.
The Queue data structure is used in situations where first added item need to be
served first. That is why this data structure is known as First-In-First-Out (FIFO) data
structure.

3
ZENEX DEGREE COLLEGE,

While adding items to a Queue, the Rear End of the Queue increases and while
deleting items from the Queue the Front End increases. Addition of items to a Queue is
possible only when the Queue is not full.
Deletion of items from a Queue is possible only when the Queue is not empty.
Queue data structures can be implemented by using either Arrays or Linked structure.
Each queue has a definite capacity called maximum size of the queue.

2.Abstract Data Type for Linear Queue using


Arrays? Abstract Data Type for Linear Queue using
Arrays: AbstractDataType Queue
{
Data Objects : A Linear List of items
MAX_SIZE : Is an integer constant which represents the maximum size of the Queue.
Front, rear :Integer variables that represent the front end and rear end
positions of the Queue.
Operations:
isEmpty() : Returns true if queue is empty, return false otherwise
isFull() : Return true if queue is full, return false otherwise
first() : Return first element of the Queue
last() : Returns last element of the Queue
add(x) : Adds element x to the Queue
delete(x) : Deletes front element from Queue and put it in x.
}

3
ZENEX DEGREE COLLEGE,

Algorithms
Algorithm: Q.insert (Q,F,R,X): [ Given F,R are pointers to the first and last elements of the
queue ‘Q’. ‘Q’ consisting of maximum element initially F & R have been set to -1]
Step: 1 [check for overflow]
If (R>=max-1) then write queue overflow
Return
Step: 2 [increment R]
R R+1;
Step: 3 [insert ‘x’ at ‘R’ in queue]
Q[R] x;
Step: 4 [if F property set]
If (F= = -1) then F 0;
Step: 5 [finish]
Return;
Algorithm: Q.delete(Q, F, R, X): [Q is a queue represented in memory for F and R are two
variables are first and last elements in a queue. This algorithm deletes and assigns the first
element of the queue to the variable x]
Step: 1 [check underflow]
if (F= =-1) then write (“queue underflow”)
Return
Step: 2 [assigns the deleted value to x]

3
ZENEX DEGREE COLLEGE,

X Q[F];
Step: 3 [updates F pointer]
If (F= = R) then F -1 [set F and R values to -1]
R -1
Else
F F+1[increment F value by 1]
Step: 4 [finish]
Return;

3. How to represent Linear Queue using Linked Representation?


A Linear Queue can be represented as a Linked List. For this we need two variables
front and rear to keep track of the two ends of the Queue. There are two possibilities for
binding these two variables to the ends of the Linked list. The nodes can be linked from
front to rear or rear to front. But linking the nodes from front to rear is more efficient for
deletions.

Abstract datatype:
AbstractDataType LinkedLinerQueue
{ Instances:
An ordered list of elements; one end is called front end and another end is called
rear end.
Operations:
isEmpty() : Returns true if the Queue is empty
first() : Returns the first element in the Queue
last() : Returns the last element in the Queue
add(x) : Adds the data element x to the Queue
delete() : Deletes an element from the Queue
}
4.Explain about CIRCULAR QUEUE?
In a general queue once an element is deleted the front pointer will be updated. So,
the memory cell from which the element is deleted will be useless. To avoid this wasteful of

3
ZENEX DEGREE COLLEGE,

memory there is another technique, is called a circular queue. This is a more suitable
method of representing a queue which prevent an excessive use of memory by arranging
the elements
Q[1], Q[2],Q[3]…….Q[N] in a circular fashion.
The logical view of a circular queue is shown as

REAR
FRONT

The Circular queue is empty, if


FRONT=0
REAR=0
The Circular queue is full ,if
REAR=N (SIZE) OR FRONT=(REAR MOD N)+1
Example:
Trace of operations on circular queue:
Fig-1
F=0
InitiallyR=t0here are no elements in the queue F=0, R=0.
FIG-2
A
F=1
R=1 When an element ‘A’ is inserted into the circular queue F=1, R=1.
FIG-3
F=1 A B
R=2 When an element ‘B’ is inserted into circular queue F=1, R=2.
FIG-4
F=1
R=3

4
ZENEX DEGREE COLLEGE,

A B C
When an element ‘C’ is inserted into circular queue F=1, R=3.
FIG-5
F=1 A B C D
WheRn=4an element ‘D’ is inserted into circular queue F=1, R=4.
FIG-6
F=1 A B C D E
R=5 When an element ‘E’ is inserted into circular queue F=1, R=5.
Circular queue is completely filled up. I.e. the over flow condition is
being satisfied we can’t insert any more elements into the circular queue.
FIG-7
F B C D E
R=4 In the above diagram when we deleted the first element A from the circular
queue. The Front point=2 and we can observe that there is a memory cell existing freely in
the first location. So, we can insert an element an element F into the first location by
setting the value of the Rear pointer to 1.This is possible because we have arranged the

4
ZENEX DEGREE COLLEGE,

elements in circular fashion. I.e. Rear=1 after Rear=n.


This can be shown in the fallowing figure:
FIG-7
F=2
R=1 F B C D E
When an element ‘F’ is inserted into circular queue F=2, R=1.

Algorithm for Inserting an element into a circular queue : (Enqueue _CQ)


CQ is an array of size N. FRONT and REAR are 2 pointers. An element ITEM to be inserted
into the circular queue.
1. if (FRONT=0)then //when the queue is empty
2. FRONT=1
3. REAR=1
4. CQ[FRONT]=ITEM
5. Else // if the queue is not full
6. next=(REAR MOD N)+1 (or )next=REAR+1
7. if (next<>FRONT)then
8. REAR=next
9. CQ[REAR]=ITEM
10. else
11. display “Circular Queue is full “
12. endif
13. endif
14. stop
Algorithm for deleting an element from the circular queue:(Dequeue_CQ)
CQ is an array of size N. FRONT and REAR are 2 pointers.
1. if (FRONT=0)then
2. Display “Circular queue is empty”
3. exit
4. else
5. ITEM=CQ[FRONT]
6. if (FRONT=REAR)then //if the circular queue contains a single element
7. FRONT=0
8. REAR=0
9. Else
10. FRONT=(FRONT MOD N)+1 ( OR) FRONT=FRONT+1
11. Endif
12.Endif
13. stop

5.What is DOUBLY ENDED QUEUE ( DEQUES) and explain their operations?


DOUBLY ENDED QUEUE ( DEQUES):
A Deque is a linear list in which elements can be added or removed at either “end” but not
in the middle. The structure of Deque is shown as
FRONT REAR

Deletio
Deletion
Insertio Insertion
40
ZENEX DEGREE COLLEGE,

The Deque can be used as a stack as well as a queue.The Deque is represented by using
double linked list or a circular array.
OPERATIONS ON A DEQUE:
1.push_DQ(ITEM): To insert ITEM at the FRONT end of deque.
2.Pop_DQ(): To remove the FRONT item from a deque.
3.Inject(ITEM):To insert ITEM at the REAR end of a deque.
4.Eject_DQ():To remove the REAR ITEM from a deque.
The above operations are described for a deque using circular array of length N. Let array
be DQ[1…….N]
Algorithm for push _DQ(ITEM): The ITEM to be inserted at FRONT.
1. if (FRONT=1) then // if FRONT is at extreme left
2. ahead=N
3. Else // if FRONT is at extreme right or the deque is empty
4. If (FRONT=N) or (FRONT=0) then
5. ahead=1
6. Else
7. ahead=FRONT-1 //FRONT is an intermediate position
8. Endif
9. If (ahead=REAR) then
Display “Deque is full or underflow” Exit
10. Else
11. FRONT=ahead
12. DQ[FRONT]=ITEM //push an ITEM
13. Endif
14. Endif
15. stop
Algorithm for Pop _DQ(): Remove FRONT item from a deque.
This algorithm is same as algorithm for Dequeue_CQ (that is deleting an element from the
circular queue)
Algorithm for Inject(): Insert an item at REAR end of a deque.
This algorithm is same as algorithm for Enqueue_CQ (that is inserting an element in to a
circular queue)
Algorithm for Eject _DQ(): Remove REAR ITEM from a deque.
1. If (FRONT=0) then
2. Display “Deque is empty or underflow”
3. Exit
4. Else
5. If (FRONT=REAR)then //the deque contains a single element
a. ITEM=DQ[REAR]
b. FRONT=REAR=0 //deque becomes empty
6. Else
a. If (REAR=1)then //REAR is extreme left
i.ITEM=DQ[REAR]
ii.REAR=N
b. Else
c. If (REAR=N)then //REAR is extreme right
i.ITEM=DQ[REAR]
ii.REAR=1

4
ZENEX DEGREE COLLEGE,

d. Else //REAR is at intermediate position


i.ITEM=DQ[REAR]
ii.REAR=REAR-1
e. Endif
f. Endif
g.Endif 7.Endif. 8.Stop
6.Define PRIORITY QUEUE (PQueue)?
A priority queue is a data structure in which prioritized insertion and deletion
operations on elements can be performed according to their priority values.
(or)
A PQueue or priority queue is a collection of elements such that each element has been
assigned a value,called the priority of the element,and an element can be inserted or
deleted not only at the ends, but at any position on the queue. The elements of priority
queue are processed(inserted or deleted) according to the following two rules.
1. The element of higher priority is processed before any element of lower priority.
2. Two elements with the same priority are processed according to the order in which they
are added to the queue.
Example: An example of priority queue is a time sharing operating system.
IMPLEMENTATION OF A PRIORITY QUEUE: The Priority queue is implemented by using
different structures. They are
1.Using a simple or circular array
2.Multi_queue implementation
3.Using a double linked list
4.Using Heap Tree

7.How to implement Priority Queue using an array?


Priority Queue using an array: With this representation, an array can be maintained to
hold the item and its priority value. The element Will be inserted at the REAR end as usual.
The deletion operation will be performed as:
(i) Starting from FRONT pointer, traverse the array for an element of the highest priority.
Delete this element from the queue. If this is not the front most element, shift all its
trailing elements after the deleted element to fill up vacant position.
Insertion algorithm:
1. if (REAR>=N-1) (Queue Size)
Print” Queue Overflow”
2. Other wise we can read the data and priority
Read t.data, t.p (data->value, p->priority)
3. The entered number is the first element to store in a queue then
REAR=REAR+1
Q[REAR] =t
4. If the element is not a first element then we can check the priority number, and the
priority number is greater than then we have to place the element in the end of the queue.
For(k=FRONT+1;k<=REAR;k++)
If(t.p<Q[k].p)
Break
For(j=REAR+1;j>=k;j--)
Q[j]=Q[j-1]
Q[k]=T
REAR=REAR+1

4
ZENEX DEGREE COLLEGE,

Deletion algorithm:
check the REAR and FRONT same or not
if (REAR=FRONT)
Print” Queue Under flow”
2. Other wise we can delete the front end element.

8. How to implement Priority Queue using Linked Lists?


Priority Queue using Linked Lists: This representation assumes the node structure as:
With this structure, to delete an item having priority p, the list will be searched starting
from the node under pointer REAR and the first occurring node with Priority=p will be
deleted. Similarly, to insert a node containing an item with priority p, the search will begin
from the node under the pointer FRONT and the node will be inserted before a node found
first with priority value p, or if not found then before the node with the next priority value.
Algorithm for inserting an element into priority queue(Insert_PQ):
1. Ptr=HEADER //start from the header
2. new=getnode(NODE) //Create a new node
3. newDATA=ITEM
4. newPRIORITY=p
5. while (ptrRLINK<>NULL)and (ptrPRIORITY<P)do //search for position
6. ptr=ptr->RLINK
7. Endwhile
8. if ( ptrRLINK=NULL)then //if the list is empty or the item with largest
priority value
9. ptrRLINK=new
10. newLLINK=ptr
11. newRLINK=NULL //the node is inserted as last node
12. REAR=new
13. Else
14. If (ptrPRIORITY>=P)then //First occurrence is found
15. ptr1=ptr->LLINK //insert a new node
16. ptr1RLINK=new //before a node with priority>P
17. newRLINK=ptr
18. ptrLLINK=new
19. newLLINK=ptr1 ,20.end if
21.FRONT=HEADER->RLINK //set the FRONT pointer
22.stop

Algorithm for deleting an element from the priority queue


(Delete_PQ):
1. if (REAR=NULL)then
2. display “Priority queue is empty”
3. exit
4. else
5. ptr=REAR
6. while (ptr->PRIORITY>P) and (ptr<>HEADER) do
7. ptr=ptr->LLINK
8. Endwhile
9. If (ptr=HEADER) or (ptr->PRIORITY<P)
10. Display “no item with this priority”

4
ZENEX DEGREE COLLEGE,

11. exit
12. Else
13. If(ptr->PRIORITY=P)then
14. ptr1=ptr->LLINK
15. ptr2=ptr->RLINK
16. If (ptr=REAR) //if the last node to be deleted
17. REAR=ptr1
18. ptr1->RLINK=NULL
19. Else //other than last node deleted
20. ptr1->RLINK=ptr2
21. ptr2->LLINK=ptr1
22. Endif
23. Endif
24. Endif
25. ITEM=ptr->DATA
26. Returnnode(item)//remove ITEM
27. Endif
28. Stop

9. DIFFERENCES BETWEEN STACK AND QUEUE?


STACK QUEUE
1. Stack is the linear list of elements 1. Queue is a linear list of elements in
may be inserted or deleted at one which the elements are added at one
end(called top). end(called Rear)or deleted at the other
2.Stack representation diagram end(called Front).
3. In stack the element which is 2. Queue representation diagram
inserted last is the first element to be 3. In queues the element which is
deleted. inserted first is the element to be
4.Stacks are called last in first out list deleted first.
(LIFO). 4.Queues are called first in first out list
5. In stack elements are removed in (FIFO)
reversed order in which they are 5. In queues elements are removed in
inserted. the same order in which they are
6. In stack there is only pointer (top) to inserted.
insert or delete. 6. In queues they are two pointers
7.Ex: for stack (rear, front) one pointer is for insertion
8.no different types of stacks and another pointer is for deletion.
9.write stack applications 7. Ex: for queues
8.There are different types of queues
like circular queue, dequeue,priority
queue.
9.write queue applications

10. What are the Applications of


queues? Applications of queues:-
The following are the important applications of a queue.
1. Time sharing operating system in which CPU is scheduled for different jobs.
2. Queue is used in page replacement algorithm of an operating system.

4
ZENEX DEGREE COLLEGE,

3. Queues are also used in multi-programming operating system (o.s) in which it is used to
hold a set of programs ready for execution. Queues are used in BFT of a graph.

Important Questions:
1.How to represent Stack using Linked List and explain their operations?
2.Implementations of Stacks?
3. CONVERSION OF AN INFIX EXPRESSION TO POSTFIX EXPRESSION?
4. How to represent Linear Queue using Linked
Representation? 5.Explain about CIRCULAR QUEUE?
6. What is DOUBLY ENDED QUEUE ( DEQUES) and explain their operations?
7. How to implement Priority Queue using Linked
Lists? 8.DIFFERENCES BETWEEN STACK AND QUEUE?

4
ZENEX DEGREE COLLEGE,

UNIT –III
TREES
1.What is a Tree and explain?
Tree is a non-linear data structure. In which the items(elements) are not organized in a
linear order. That means the items are organized in a hierarchical form like a tree
structure.

Definition: A tree is a collection of nodes. The collection can be empty or non-empty. If not
empty, a tree consists of a distinguished node R (the root), and zero or more nonempty
subtrees T1, T2, ...., Tk, each of whose roots are connected by a directed edge from R. There
is a specially designed node called a Root node. The remaining nodes are partitioned into
n>=0 disjoint sets called T1, T2, T3------------------------------TN. Where each of these sets is a
tree. Here T1, T2 ,…TN can be called as sub trees.`

For example:-

Root node

The above figure represents a simple tree. In this figure root node is A, and the remaining
three sub trees rooted at B, C and D. Sub tree D is a leaf node, as are the remaining nodes
E,F,G,H and I. the node C has a single child I, where as E,F,G and H have the same parent B.
Tree Terminology:
Root: The root is a specially designated node ,which has no parent. In the above example

4
ZENEX DEGREE COLLEGE,

node A is the ROOT.


Node: This is the main component of any tree structure. The node of a tree stores the
actual data and its role is same as in the linked list. Nodes are connected by the means of
links with other nodes. The structure of a node in a tree is shown as:
LEFTCHILD DATA RIGHTCHILD
(LC) (RC)
Example:

Parent: It is the immediate predecessor of a node. In the above figure A is the parent of B
,C,D and B is the parent of E,F,G.
Child: If the immediate predecessor of a node is the parent of the node then all immediate
successors of a node are called as child’s. In the above example The nods B,C,D are the
Childs of node A.
Degree of a node: The maximum number of children that exists for a node is called
the degree of the node.
Degree of a tree: The maximum degree of the nodes in a tree is called degree of a tree.

Leaf nodes (or) terminal nodes:


A Node in a tree ‘T’ whose degree is zero or who has no sub trees are called terminal nodes
or leaf nodes. In the above example E,F,G,H,I,D are the leaf nodes.(or)
Ancestors: The ancestors of a node are all the nodes along the path from the root to that
tree.
Sibling: The nodes which have the same parent are called siblings. They are also called
brother nodes.
Level of a node: Level is the rank in the hierarchy. The root node has level 0.If a node is
at level L ,then its child is at level L+1 and the parent is at level L-1.
Height or depth of a tree: The maximum number of nodes that is possible in a path
starting from the root node to a leaf node is called the height or depth of a tree.
Forest: It is a group of disjoint trees. If we remove a root node from a tree then it becomes
the forest. In the following example, if we remove a root A then 3 disjoint sub- trees will be
observed. They are sub trees B,C,D.
1. Degree of a node B=3, C=1, I=0.
2. Degree of a tree=3(max degree of any node =3)
3. Leaf nodes are E, F, G & D, I, J
4. B, C, D is siblings.
E, F, G
I, J
5. Ancestors of G are A, B
6. Level of A=0
7. Height or depth of the tree=4
2. What is Binary tree and what are the types of Binary
Tress? Binary Tree:
A binary tree is an important type of tree structure and frequently used in various
applications of computer science. In a binary tree, the node can have at most two

4
ZENEX DEGREE COLLEGE,

children, i.e. the maximum degree of any node is =2. A binary tree can be defined as a
finite set of nodes ,such that
(i) Tree (T) is empty(called the empty binary tree) or
(ii) Tree(T) contains a specially designated node called the root of T, and the remaining
nodes of T form two disjoint binary trees t1 and t2 which are called the left sub-tree and
the right sub-tree, respectively.

Examples:

Types of binary trees:


Full binary tree:
A binary tree is a full binary tree if it contains the maximum possible number of nodes at all
levels.
Example:

Complete binary tree: A binary tree is a tree is said to a complete binary tree if all its
levels, except possibly the last level, have the maximum number of possible nodes, and all
the nodes in the last level appear as far left as possible.
Example:

3.Briefly discuss about ADT: Binary Trees ?


ADT: Binary Trees :Binary trees are relatively simple to understand and reasonably
straight forward to program because they use standard algorithms.
1. Design of an Binary Tree ADT
A binary tree consists of one or more Nodes, each one of which is able to point to
(reference) another node of the same type:.

4
ZENEX DEGREE COLLEGE,

4. What are the Properties of Binary Trees:


A binary tree has a number of properties. These properties are very much useful and are listed
below,
 The number of nodes at depth d in a perfect binary tree = 2d+1-1

 The maximum number of nodes on level l is 𝟐𝒍, where l ≥0.


 The number of leaf nodes in a perfect binary tree of height h = 2h

 The maximum no.of nodes possible in a binary tree of height h is 2h+1 -1.
 The minimum no.of nodes possible in a binary tree of height h is h+1.
 The number of internal nodes in a perfect binary tree of height h = 2h – 1

 The height of the complete binary tree with n no.of nodes is [ log2( 𝑛 + 1)].
 For any non empty binary tree, if n is the no.of nodes and e is the no.of edges then n=e-1.

 The total number of binary trees possible with n nodes is 1 2n C .


𝑛−1 n

Level (l ) Node ( 2l)


0 20 =1
1 21=2
2 22=4
3 23=8
Height of the tree h =3
Depth of the tree d = 3

5. Discuss about Binary Tree Representation


? Binary Tree Representation:
This section discusses two ways of representing binary tree T in memory:
1. Sequential representation using arrays
2. Linked list representation
Sequential representation using arrays :
Linear search is a very simple search algorithm. In this type of search, a sequential search
is made over all items one by one. Every item is checked and if a match is found then that

4
ZENEX DEGREE COLLEGE,

particular item is returned, otherwise the search continues till the end of the data
collection.

Algorithm:-
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
LINKED LIST REPRESENTATION :
The most popular and practical way of representing a binary tree is using linked list(or
pointers). In linked list, every element is represented as nodes. A node consists of three
fields such as :
a) Left Child (LChild)
(b) Information of the Node (Info)

5
ZENEX DEGREE COLLEGE,

(c) Right Child (RChild)

6. What are the Applications of


trees? Applications of trees:-
1. In computer science, trees are used to organise information in hierarchal structure in
the data base systems.
2. Trees are used to represent the synaptic structure of source program in compilers.
3. Trees are used in conversions of the in-fix expression to post-fix 9or) pre-fix
expression.
4. Trees are used in o.s level to view the directory list in.
5. Trees are used to analyse networking circuits.

7. What is Binary Search tree(BST) and explain their


operations? Binary Search Tree

5
ZENEX DEGREE COLLEGE,

Def: Binary Search tree exhibits a special behavior.


A node's left child must have a value less than its
parent's value and the node's right child must have
a value greater than its parent value.

BST Operations
The basic operations that can be performed on a binary search tree data structure, are the
following –
 Insert − Inserts an element in a tree/create a tree.
 Delete-Delete an element from a tree.
 Search − Searches an element in a tree.
 Preorder Traversal − Traverses a tree in a pre-order manner.
 Inorder Traversal − Traverses a tree in an in-order manner.
 Postorder Traversal − Traverses a tree in a post-order manner.

Insertion: This operation is used to insert a new node into the binary tree. The insertion
procedure contains two-steps.
Step-1: First we search for the existence of a node
in the given binary tree.
Step-2: Next we insert a node by establish a link for
the new node.
The following Figure shows how a new node G to a leaf
node containing data content E.

Deletion:
This operation is used to delete any node from any non-empty binary tree. The deletion
operation also varies from one kind of binary tree to another. Consider the case of deletion
of a leaf node in any binary tree. The following Figure shows how a leaf node containing
data G can be deleted from a binary tree.

Search Operation
Whenever an element is to be searched, start searching from the root node, then if the
data is less than the key value, search for the element in the left subtree. Otherwise,

5
ZENEX DEGREE COLLEGE,

search for the element in the right subtree. Follow the same algorithm for each node.
Algorithm:-
If root.data is equal to
search.data return root
else
while data not found
If data is greater than
node.data goto right subtree
else
goto left
subtree If data
found return
node endwhile
return data not
found end if

7. Explain about Binary Search Tree


Traversals? Traversals:
Traversal is a process to visit all the nodes of a tree and may print their values too. All
nodes are connected via edges (links) we always start from the root (head) node. That is,
we cannot randomly access a node in a tree. There are three ways which we use to traverse
a tree −
a) In-order Traversal
b) Pre-order Traversal
c) Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree or to print
all the values it contains.

In-order Traversal:
In this traversal method, the left child is visited first, then the parent and later the right
child. The output of in-order traversal of this tree will be : D → B → E → A → F → C → G

Algorithm:

5
ZENEX DEGREE COLLEGE,

Let BT be a Binary Tree. ROOT points to the root node, LC is the link to left child and RC is
the link to right child.
1. Start
2. If (ROOT=NULL) then
3. Print “ Tree is empty”
4. Else
5. Inorder(ROOT.LC)
6. Visit(ROOT)
7. Inorder(ROOT.RC)
8. Endif
9. Stop

Pre-order Traversal:

In this traversal method, the parent(root) node is visited first, then the left child and finally
the right child. The output of pre-order traversal of this tree will be: A → B → D → E → C → F
→G

Algorithm:
Let BT be a Binary Tree. ROOT points to the root node, LC is the link to left child and RC is
the link to right child.
1. Start
2. If (ROOT=NULL) then
3. Print “ Tree is empty”
4. Else
5. Visit(ROOT)
6. Preorder(ROOT.LC)
7. Preorder(ROOT.RC)
8. Endif
9. Stop

Post-order Traversal:

In this traversal method, the left child is visited first, then right child is visited and last
parent is visited. The output of inorder traversal of this tree will be : D → E → B → F → G →
C→A

Algorithm:

5
ZENEX DEGREE COLLEGE,

Let BT be a Binary Tree. ROOT points to the root node, LC is the link to left child and RC is
the link to right child.

1. Start
2. If (ROOT=NULL) then
3. Print “ Tree is empty”
4. Else
5. Postorder(ROOT.LC)
6. Postorder(ROOT.RC)
7. Visit(ROOT)
8. Endif
9. Stop

8. Representation of Binary Trees:


A binary tree can be represented in two ways. They are,
a) Representation using Arrays.
b) Representation using Linked List.

a) Binary Tree Representation using Arrays:

In the array representation of binary trees, we use an array to store the nodes of a binary
tree. The nodes stored in an array of memory can be accessed sequentially.
In this representation, the nodes are stored level by level, starting from the zero level
where only the root node is present. The root node is stored in the first memory location (as
the first element in the array).
Following rules can be used to decide the location of any node of a tree in the array
(assuming that they array index starts from 1):
1. The root node is at location 1.
2. For any node with index i, 1 < i ≤ n (for some n):
a. PARENT(i) = [i/2]
For the node when i = 1, there is no parent.
b. LCHILD(i) = 2 * i
If 2 * i > n, then i has no left child.
c. RCHILD = 2*i+1
If 2 * i + 1 > n, then I has no right child.

Suppose a binary tree T of depth d. Then at most 2d – 1 nodes can be there in T(i.e., SIZE
= 2d–1). So we require the array of size “SIZE” to represent the binary tree.

Consider binary trees as shown below. The first binary tree has three elements (A, B, and
C), and the second has five elements (A, B, C, D, and E). White circles represent missing
elements. Dark circles contains element.

5
ZENEX DEGREE COLLEGE,

The above two binary tree has degree 3 then SIZE=23 – 1=7.
Therefore, we require an array A[7] to hold nodes. The white boxes
in the array represent missing nodes and gray boxes represent nodes in the binary tree.

b) Binary Tree Representation using Linked List:


The most popular and practical way of representing a binary tree is using linked list. In
linked list, every element is represented as nodes. A node consists of three
fields such as :
 Left Child (LC)
 DATA
 Right Child (RC)

Here, LC and RC are the two link fields used to store the addresses of left child and right
child of a node; DATA is the information content of the node. With this representation, if we
know the address of the root node then from it any other node can be accessed.
The following figure shows the linked representation of a binary tree containing ten nodes.

Structure of a node in
linked representation.

Each LC and RC link fields in a node store the addresses of left child and right child of a
node. The LC and RC link fields in a leaf node are NULL.

5
ZENEX DEGREE COLLEGE,

Important Questions:
1. What is Binary tree and what are the types of Binary
Tress? 2.Briefly discuss about ADT: Binary Trees ?
3.What are the Applications of trees?
4.Explain about Binary Search Tree Traversals?
5.What is Binary Search tree(BST) and explain their operations?

5
ZENEX DEGREE COLLEGE,

UNIT – IV
GRAPHS
Introduction
Graph is a non linear data structure which contains a set of points known as nodes (or
vertices) and set of links known as edges (or Arcs) which connects the vertices.
A Graph is a collection of vertices and arcs which connects vertices in the graph. Graph is a
collection of nodes and edges which connects nodes in the graph.
Generally, a graph G is represented as G = (V, E), where V is set of vertices and E is set of
edges.
G=(V,E)
V(G)={v0,v1,v2…..vn-1}
E(G)={e1,e2….en)
Example
The following is a graph with 5 vertices and 6 edges.
This graph G can be defined as G = (V, E )
Where V = {A,B,C,D,E} and E = {(A,B),(A,C)(A,D),(B,D),(C,D),(B,E),(E,D)}

Graph Terminology (or ) Graph Components


We use the following terms in graph data Components
Vertex
A individual data element of a graph is called as Vertex. Vertex is also known as node. In
above example graph, A, B, C, D & E are known as vertices.
Edge
An edge is a connecting link between two vertices. Edge is also known as Arc. An edge is
represented as (startingVertex, ending Vertex).
Example: In the above graph, the link between vertices A and B is represented as (A, B). In
above example graph, there are 7 edges (i.e., (A, B), (A, C), (A, D), (B,D), (B,E), (C,D),
(D,E)).
Undirected Graph
A graph with only undirected edges is said to be undirected graph.

Directed Graph
A graph with only directed edges is said to be directed graph.

5
ZENEX DEGREE COLLEGE,

Degree
Total number of edges connected to a vertex is said to be degree of that vertex.
In-degree
Total number of incoming edges connected to a vertex is said to be in-degree of that
vertex.
Out-degree
Total number of outgoing edges connected to a vertex is said to be out-degree of that
vertex.
Path
A path is a sequence of alternating vertices and edges that starts at a vertex and ends at a
vertex such that each edge is incident to its predecessor and successor vertex.
Adjacent
If there is an edge between vertices A and B then both A and B are said to be adjacent. In
other words, Two vertices A and B are said to be adjacent if there is an edge whose end
vertices are A and B.

Mixed Graph
A graph with undirected and directed edges is said to be mixed graph.
Origin
If an edge is directed, its first endpoint is said to be origin of it.
Destination
If an edge is directed, its first endpoint is said to be origin of it and the other endpoint is
said to be the destination of the edge.
Cyclic graph:- A graph that has cycles is called cyclic graph.
Acyclic graph:- a graph that has no cycles is called an acyclic graph.
Isolated graph:- if a node has no edges connected with any other node then it’s degree
will be o and it will be called isolated graph.
Self-loop
An edge (undirected or directed) is a self-loop if its two endpoints coincide.
Multi graph:- a graph which has loop or multiple edges can be described as multi graph.

1.What are the representations of Graphs in memory


explain? Representation of Graphs in memory
Graph data structure is represented using following representations:
1) Adjacency Matrix( sequential )
2) Adjacency List(linked)
1) Adjacency Matrix(Sequential Representation)

In this representation, graph can be represented using a matrix of size total number of
vertices by total number of vertices. Adjacency matrix is the matrix, which keeps the
information of adjacency nodes. The adjacency matrix A of a graph G=(V,E) with n nodes is

5
ZENEX DEGREE COLLEGE,

an MXN matrix such that,


A[i][j]= { 1 If there is an edge from node i to node j
0 if there is no edge from node I to node j }
Example:
For a Undirected graph representation the adjacency matrix representation is

For a Directed graph representation the adjacency matrix representation is

That means if a graph with 4 vertices can be represented using a matrix of 4X4 class. In
this matrix, rows and columns both represent vertices. This matrix is filled with either 1 or
0. Here, 1 represents there is an edge from row vertex to column vertex and 0 represents
there is no edge from row vertex to column vertex.
2) Adjacency List(liked Representation)
In adjacency list representation of graph, we will maintain two lists. First list will keep track
of an nodes in the graph and second list will maintain a list of adjacent nodes for each
node. It is more efficiency of than adjacency matrix.
Example: Consider the following directed graph representation implemented using linked
list

Graph Traversals Techniques(Graph Searching techniques)


Graph traversal is technique used for searching a vertex in a graph. The graph traversal is
also used to decide the order of vertices to be visit in the search process. A graph traversal
finds the egdes to be used in the search process without creating loops that means using
graph traversal we visit all vertices of graph without getting into looping path.
There are two standard graph traversal techniques:
– Depth-First Search (DFS)
– Breadth-First Search (BFS)
2.Write about Depth First Search (DFS) Traversal?

6
ZENEX DEGREE COLLEGE,

Depth First Search:- (DFS)


Depth First Search (DFS) algorithm traverses a graph in a depthward motion and stack is
used in the implementation of the depth first search.
We use the following steps to implement DFS traversal...
Step 1: Define a Stack of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex and push it on to
the Stack.
Step 3: Visit any one of the adjacent vertex of the verex which is at top of the stack which
is not visited and push it on to the stack.
Step 4: Repeat step 3 until there are no new vertex to be visit from the vertex on top of the
stack.
Step 5: When there is no new vertex to be visit then use back tracking and pop one vertex
from the stack.
Step 6: Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7: When stack becomes Empty, then produce final spanning tree by removing unused
edges from the graph

Step Traversal Description

1. Initialize the stack.

Mark S as visited and put


it onto the stack. Explore
any unvisited adjacent
node from S. We have
2. three nodes and we can
pick any of them. For this
example, we shall take
the node in an
alphabetical order.

6
ZENEX DEGREE COLLEGE,

Mark A as visited and put


it onto the stack. Explore
any unvisited adjacent
3. node from A.
Both S and D are
adjacent to A but we are
concerned for unvisited
nodes only.

Visit D and mark it as


visited and put onto the
stack. Here, we
have Band C nodes,
which are adjacent
4. to D and both are
unvisited.
However, we shall again
choose in an
alphabetical order.

We choose B, mark it as
visited and put onto the
5. stack. Here B does not
have any unvisited
adjacent node. So, we
pop B from the stack.

We check the stack top


for return to the previous
node and check if it has
6. any unvisited nodes.
Here, we find D to be on
the top of the stack.

6
ZENEX DEGREE COLLEGE,

Only unvisited adjacent


node is from D is C now.
7. So we visit C, mark it as
visited and put it onto
the stack.

As C does not have any unvisited adjacent node so we keep popping the stack until we find
a node that has an unvisited adjacent node. In this case, there's none and we keep popping
until the stack is empty.

3.Write about Breadth First Search (BFS)


Traversal? Breadth First Search:- (BFS)
Breadth First Search (BFS) algorithm traverses a graph in a breadth ward motion and
Queue is used in the implementation of the breadh first search.
We use the following steps to implement BFS traversal...
Step 1: Define a Queue of size total number of vertices in the graph.
Step 2: Select any vertex as starting point for traversal. Visit that vertex and insert it
into the Queue.
Step 3: Visit all the adjacent vertices of the verex which is at front of the Queue which is
not visited and insert them
into the Queue.
Step 4: When there is no new vertex to be visit from the vertex at front of the Queue then
delete that vertex from
the Queue.
Step 5: Repeat step 3 and 4 until queue becomes empty.
Step 6: When queue becomes Empty, then produce final spanning tree by removing
unused edges from the graph
Step Traversal Description

1. Initialize the
queue.

6
ZENEX DEGREE COLLEGE,

We start from
visiting S starting
2. nodestartingnode
, and mark it as
visited.

We then see an
unvisited adjacent
node from S. In this
example, we have
3. three nodes but
alphabetically we
choose A, mark it
as visited and
enqueue it.

Next, the unvisited


adjacent node
4. from S is B. We
mark it as visited
and enqueue it.

Next, the unvisited


adjacent node
5. from S is C. We
mark it as visited
and enqueue it.

6
ZENEX DEGREE COLLEGE,

Now, S is left with


no unvisited
6. adjacent nodes. So,
we dequeue and
findA.

From A we
have D as unvisited
7. adjacent node. We
mark it as visited
and enqueue it.

At this stage, we are left with no unmarked unvisitedunvisited nodes. But as per the
algorithm we keep on dequeuing in order to get all unvisited nodes. When the queue gets
emptied, the program is over.

4. What is Minimal Spanning Tree


(MST)? Minimal Spanning Tree (MST)

A Spanning tree is a sub-graph of G that has the same set of vertices of G and is a tree.A
Minimum spanning tree of a weighted connected graph G is its spanning tree of the
smallest weight, where the weight of a tree is defined as the sum of the weights on all its
edges. The total number of edges in Minimum spanning tree is V – 1 where V is the number
of vertices.
5. What are the algorithms to find minimal spanning Tree and
explain? Minimal Spanning tree Algorithms:
There are two algorithms for finding Minimum spanning tree
1) Prim’s algorithm
2) Kruskal’s algorithm
1) Prim’s algorithm
Prim's algorithm to find minimum cost spanning tree uses the greedy approach. Prim's
algorithm shares a similarity with the shortest path first algorithms.
Algorithm
1) One node is picked as a root node (u) from the given connected graph.
2) At each stage choose a new vertex v from u, by considering an edge (u, v) with
minimum cost among all the edges from u, where u is already in the tree and v is not in
the tree.
3) The Prim’s algorithm table is constructed with three parameters. They are:
Known – Vertex is added in the tree or not.

6
ZENEX DEGREE COLLEGE,

dv –Weight of the shortest arc connecting v to a known vertex.


Pv – last vertex which causes a change in dv
4) After selecting the vertex v, update rule is applied for each unknown w adjacent to v.
The rule is dw=Min (dw, Cw,v) that is if more than one path exist between v to w, then d w is
updated with minimum cost.
Example:
For the following graph construct Minimum spanning tree using Prim’s algorithm.

2) Kruskal’s algorithm
Kruskal's algorithm is an algorithm in graph theory that finds a minimum spanning tree for
a connected weighted graph. This means it finds a subset of the edges that forms a tree
that includes every vertex, where the total weight of all the edges in the tree is minimized.
If the graph is not connected, then it finds a minimum spanning forest (a minimum
spanning tree for each connected component). Kruskal's algorithm is an example of a
greedy algorithm.
Algorithm:
1) Start by selecting the two nodes with the minimal costing link.
2) Select any two nodes with the minimal costing link. Your selection is not bound by any
requirement to
select nodes connected to previously selected nodes. Any two nodes we can select, as
long as it the
minimal cost.
3) Repeat steps 1 and 2 until all nodes have been selected / connected.
Example:

6
ZENEX DEGREE COLLEGE,

Solution:

6
ZENEX DEGREE COLLEGE,

6
ZENEX DEGREE COLLEGE,

UNIT – V
Sorting & Searching

Sorting terminology
Sorting is one of the most important and fundamental operations performed in
computer science. It is the task of rearranging data in an order such as Ascending,
Descending or Lexicographic order. Here the data may be of any type like numerical,
alphabetical or alphanumeric. The task sorting is done more frequently in the world of
computer science. Sorting is important for the following reasons.
1. How to rearrange a given set of data?
2. What kind of data structures are suitable to store data prior to their sorting?
3. How fast can the sorting be achieved?
4. How to sort various types of data values?

Basic Terminology
Internal Sorting: When a set of data to be stored in small enough such that the entire
sorting can be performed in a computer’s internal storage(primary memory) then the
sorting is called ‘Internal Sort’.

External Sort: Sorting of a large set of data, which is stored in external memory(such as
hard disk) is called ‘External Sorting’.

Ascending Order: An arrangement of data is in increasing order of elements is called


ascending order . if Ai and Aj are two data items and Ai proceeds Aj then Ai<= Aj.
Eg: {1, 2, 3, 4, 5, 6, 7, 8}
Descending Order: An arrangement of data is in decreasing order of elements is called
descending order . if Ai and Aj are two data items and Ai proceeds Aj then Ai>= Aj.
Eg: {8, 7, 6, 5, 4, 3, 2, 1}
Lexicographic Order: Arranging character or string data values into dictionary order is
known lexicographic order. Eg: {Ant, Bat, Cat, Doll, Egg}
Swap:
Swap between two data storages implies the interchange of their contents.
Eg: Before Swap a[1] = 10 a[2] = 20
After Swap a[1] = 20 a[2] = 10.
Sorting Methods:
There are several sorting methods/strategies available to sort data in computer data
processing. Each method follows a different strategy/algorithm to sort data.
1. Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Merge Sort
5. Quick Sort

SORTING AND SEARCHING


Sorting:
Sorting is the process of arranging a list of elements in a particular order i.e., either in ascending or
descending order.

6
ZENEX DEGREE COLLEGE,

The operation of sorting is the most common task performed by computers today. Sorting is
used to arrange names and numbers in meaningful ways.
Let A be a list of n elements A 1, A2, ....... An in memory. Sorting of list A refers to the operation of
rearranging the contents of A so that they are in increasing (or decreasing) order (numerically or
lexicographically); A1 < A2 < A3 < < An.

For example, suppose an array A contains 5 elements 20, 40, 50, 30, 10. The elements of an
array can be sorted in any specified order i.e., either in ascending order (10, 20, 30, 40, 50) or
descending order (50, 40, 30, 20, 10).

Sorting can be performed in many ways. There are several methods (or algorithms) for sorting data.
The following are the most common and popular sorting algorithms.
a) Bubble sort d) Quick sort
b) Selection sort e) Merge sort
c) Insertion

1. Bubble Sort:
Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in
which each pair of adjacent elements is compared and the elements are swapped if they are not in
order. This algorithm is not suitable for large data sets.
Algorithm:
Let A be a linear array of n numbers. Temp is a temporary variable for swapping (or interchange) the
position of the numbers.

Steps:
1. Start.
2. Input n numbers of an array A.
3. Repeat for i = 0 to (i < n)
4. Repeat for j = 0 to (j < n – i – 1)
5. If (A[j] > A[j + 1]) then swap(A[j], A[j+1]).
(a) Temp = A[j]
(b) A[j] = A[j + 1]
(c) A[j + 1] = Temp
6. End if
7. End for
8. Display the sorted numbers of array A.
9. Exit.

Bubble Sort Working:


Let A be a linear array of N numbers. Sorting of A means rearranging the elements of A in
ascending or descending order. Suppose A[1], A[2],.............A[N] are N elements of an array A. Let us
sort Array in ascending order. i.e., A[1] < A[2] < A[3] <...........A [N].
The bubble sort algorithm works as follows:
 Compare first two elements of an array A[1] and A[2]. If A[1] > A[2] then arrange them in the
ascending order by swap A[1] and A[2] otherwise leave them.
 Then, again compare A[2] and A[3], if A[2] > A[3] then swap A[2] and A[3]. Continue the
process until we compare A[N-1] with A[N].
 If the array has n elements, then we must repeat above process (n-1) times.
 After n – 1 steps, the array will be a sorted array in ascending order.

Example:

7
ZENEX DEGREE COLLEGE,

Consider an unsorted array, -2, 45, 0, 11, -9. This array is sorted using Bubble Sort as shown below,
2. Selection Sort:
The

selection sort algorithm is a very important sorting technique based on the principle of Selection. A
selection sort has two important operations. They are,
1. Select : Selection of the item from the input list.
2. Swap : Interchange two items in the list.

Selection sort uses above two operations repeatedly and sorts the given array by finding and
selecting the minimum element from the unsorted array and placing it at the beginning of the array.

Algorithm:
Let A be a linear array of n numbers. Temp is a temporary variable for swapping (or interchange) the
position of the numbers.
Steps:
1. Start.
2. Input n numbers of an array A.
3. Repeat for i = 0 to (i < n)
4. Repeat for j = i+1 to (j < n)
5. If (A[i] > A[j]) then swap(A[i], A[j]).
(a) Temp = A[i]
(b) A[j] = A[j]
(c) A[j] = Temp
6. End If and For
7. Display the sorted numbers of array A.
8. Exit.

Selection Sort Working:


Let A be a linear array of N numbers. Sorting of A means rearranging the elements of A in
ascending or descending order. Suppose A[1], A[2],.................A[N] are N elements of an array A. Let us
sort Array in ascending order. i.e., A[1] < A[2] < A[3] <...........A [N].
The Selection Sort algorithm works as follows:
 Step-1: Compare first two elements of an array A[1] and A[2]. If A[1] > A[2] then arrange
them in the ascending order by swap A[1] and A[2] otherwise leave them.

7
ZENEX DEGREE COLLEGE,

o Then, again compare first element and third element compare A[1] and A[3], if A[1] >
A[3] then swap A[1] and A[3]. Continue the process until first and last element of an
array is compared A[1] with A[N]. This completes the first step of selection sort.
 Step-2: In second step, we start comparison from second element because after first phase,
the sorted number is automatically placed at the first position of the array.
 Step-3: Similarly, in third phase, we start comparison from third element and so on.
 Step-4: If the array has n elements, then we must repeat above process (n -1) times. After (n
-1) step, the array will be a sorted array in ascending order.

Example:
Consider an unsorted array 20, 12, 10, 15,2. The array is sorted using Selection Sort as shown below,

3.

Insertion Sort:
The insertion sort algorithm is a very simple and efficient sorting technique based on the principle of
Insertion. The insertion sort algorithm finds the minimum element from the unsorted array and finds
the location it belongs within the sorted list, and inserts it there. It repeats this process until all the
elements are arranged in sorted order.

Algorithm:
Let A be a linear array of n numbers. Temp is a temporary variable for swapping (or interchange) the
position of the numbers.
Steps:
1. Start.
2. Input n numbers of an array A.
3. Repeat for i = 0 to (i < n)
4. Key=a[i]
5. Set j = i-1
6. Repeat while ((key<a[j] && (j>=0) )
a. A[j+1]=A[j]
b. Set j=j-1
7. End while
8. A[j+1] = key;
9. End for

7
ZENEX DEGREE COLLEGE,

10. Display the sorted numbers of array A.


11. Exit.

Insertion Sort Working:


Let A be a linear array of N numbers. Sorting of A means rearranging the elements of A in
ascending or descending order. Suppose A[1], A[2],.................A[N] are N elements of an array A. Let us
sort Array in ascending order. i.e., A[1] < A[2] < A[3] <...........A [N].
The Insertion Sort algorithm works as follows:
 Step 1: The second element of an array is compared with the elements that appear before it.
If the second element is smaller than first element, second element is inserted in the position
of first element. After first step, first two elements of an array will be sorted.
 Step 2: The third element of an array is compared with the elements that appears before it
(first and second element). If third element is smaller than first element, it is inserted in the
position of first element. If third element is larger than first element but, smaller than second
element, it is inserted in the position of second element. If third element is larger than both
the elements, it is kept in the position as it is. After second step, first three elements of an
array will be sorted.
 Step 4: If the array has n elements, then we must repeat above process (n -1) times. After (n
-1) step, the array will be a sorted array in ascending order.

Example:
Consider an unsorted array 12, 3, 1, 5, 8. The array is sorted using Insertion Sort as shown below,

7
ZENEX DEGREE COLLEGE,

4. Merge Sort:
Merge sort is a sorting technique based on divide and conquer technique. In this algorithm, we break
down the list into several sub-lists until each sub-list consists of a single element and merge these
sub-lists in a manner that they are in a sorting order.
Merge Sort perform the following three tasks recursively. They are,
1. Divide
2. Conquer
3. Combine

Let a list of n elements to be sorted with l and r being the position of leftmost and rightmost

𝑛
Partition the list midway, that is, at [ ] ] elements in
elements in the list. The three tasks in this divide – and - conquer technique are stated as follows.
𝒍+
𝒓
2
𝟐 [
Divide:
each. If n is even or [ ] .
𝑛
into two sub-lists with

2
[ ]
𝑛
2
If n is odd -1
Conquer: Sort the two lists recursively using the merge sort.
Combine: Merge the sorted sub-lists to obtain the sorted output.
Algorithm: MergeSort
Let A be a linear array of n to be sorted with l and r be the lower and upper end indexes of A. TEMP
be temporary array.

Steps:
1. Start
2. If (r≤l) then return.
3. Else
4. mid = (low + high)/2; // Divide

7
ZENEX DEGREE COLLEGE,

5. MergeSort(a, low, mid); // Conquer Left – part


6. MergeSort(a, mid, high); // Conquer Right – part
7. Merge(a,l,mid,r) // Combine: Merge left & Right parts.
8. Endif
9. Stop

Algorithm: Merge
1. Start
2. i = low, j = mid;
3. Repeat for k = 0 to k < N
4. if (i == mid) then
5. TEMP[k] = a[j++];
6. else if (j == high) then
7. TEMP [k] = a[i++];
8. else if (a[j]<a[i]) then
9. TEMP [k] = a[j++];
10. else
11. TEMP [k] = a[i++];
12. Endif
13. Endfor
14. Repeat for k = 0 to k < N
15. A[low + k] = TEMP[k];
16. Endfor
17. Stop
Merge Sort Working:
Let A be a linear array of N numbers. Sorting of A means rearranging the elements of A in ascending
or descending order. Suppose A[1], A[2],.................A[N] are N elements of an array A. Let us sort Array
in ascending order. i.e., A[1] < A[2] < A[3] <..........A [N].
1. First divide the list of unsorted elements into two parts. Left half and Right half.
2. Apply the merge sort again and divide the left part elements in to sub lists until it become
single element.
3. Similarly divide right half of array or list of elements in to sub lists until it becomes one
element in list.
4. After dividing all elements in two parts in to single entity.
5. Merge the elements by comparing lesser element will be first. Apply same at right half.
6. Merge all the elements in the left and right parts until it become a single sorted list.

Example:
Consider an unsorted array 6, 2, 4, 5, 1, 3. The array is sorted using Merge Sort as shown below,

7
ZENEX DEGREE COLLEGE,

5. Quick Sort:
Quick Sort is
sorting
techniques based on divide and conquers technique. In this algorithm, first we select the breaking
point and we break down the list into several sub-lists until each sub-list consists of a single element
and sorts the each part and simply combines to generate a sorted array.
Quick Sort performs the following tasks recursively. They are,
1. Choose a pivot value: First we choose an element as pivot value. This value can be first or
middle or last element.
2. Divide: Rearrange elements in such a way, that all elements which are lesser than the pivot
gos to the left part of the array and all elements greater than the pivot, go to the right part of
the array. Values equal to the pivot can stay in any part of the array.
3. Conquer: Sort the two lists by apply Quick Sort algorithm recursively to the left and the right
parts.
4. Combine: Since the sub-arrays are sorted in the place, there is no need to combine.

Algorithm: Quick Sort


Let A be a linear array of n to be sorted with low and high be the lower and upper end indexes of A.
TEMP be temporary variable. Pivot is the pointer used for partitioning the list.
Steps:
1. Start
2. Set i = low, j = high;
3. Set pivot = A[(low + high) / 2];
4. Repeat while (i <= j)
5. Repeat while (A[i] < pivot) i++;
6. Repeat while (A[j] > pivot) j--;
7. if (i <= j) then

7
ZENEX DEGREE COLLEGE,

8. temp = A[i];
9. A[i] = A[j];
10. A[j] = temp;
11. i++; j--;
12. Endif
13. [Recursively sort lower half]
if (low < j) QuickSort(A, low, j);
14. [Recursively sort upper half ]
if (i < high) QuickSort(A, i, high);
15. End

Quick Sort Working:


Let A be a linear array of N numbers. Sorting of A means rearranging the elements of A in ascending
or descending order. Suppose A[1], A[2],.................A[N] are N elements of an array A. Let us sort Array
in ascending order. i.e., A[1] < A[2] < A[3] <..........A [N].
1. First we select an element in the list as pivot element (A[1] or A[n]).
2. Next we divide the list into two parts such that all the elements less than pivot is stored in the
left sub-array and all the elements greater than pivot are stored in the right sub-array.
3. Again we choose pivot in the left sub-array and repeat step-2 again.
4. Similarly we select pivot in the right sub-array and repeat step-2 again.
5. This process continues until we get a single element in the sub-arrays.
6. At the end of this process, we combine all the single elements and pivot values to get a
sorted array.

Example:

7
ZENEX DEGREE COLLEGE,

Consider an unsorted array 55, 88, 22, 99, 44, 11, 66, 77, 33. The array is sorted using Quick Sort
as shown below,

Searching
What is searching? Write about sequential or linear search?
Searching is a process of checking and finding a required element in a list of
elements. Let A be a collection of data elements, i.e., A is a linear array of say n elements. If we want
to find the presence of an element “data” in A, then we have to search for it. The search is
successful if data does appear in A and unsuccessful if otherwise. There are several types of
searching techniques; one has some advantage(s) over other. Following are the important searching
techniques:
1. Linear or Sequential Searching
2. Binary Searching

Linear or Sequential Searching:


In linear search, each element of an array is read one by one sequentially and it is compared with
the desired key element. If the key element is found in the list, the search is unsuccessful otherwise
search is unsuccessful. This algorithm terminates when the key element first occurs.

Algorithm: Linear Search


Let A be an array of n elements. Key is the element to be searched. Then this algorithm will find the
location “loc” of key in A.
Steps:
1. Start
2. Input an array A of n element.
3. Input Key value.
4. Initialize loc =0.
5. Repeat for i=0 to i<n .
6. If (Key = A[i]) then loc = i
7. Endif

7
ZENEX DEGREE COLLEGE,

8. If (loc≠ 0) then
 Print “Key Element found in the list.”
9. Else
 Print “Key Element found in the list.
10. Stop

What is searching? Write about Binary search?

Binary Search:
Binary search is an extremely efficient algorithm when it is compared to linear search. Binary search
technique searches “Key” in minimum possible comparisons. Suppose the given array is a sorted
one, otherwise first we have to sort the array elements. Then apply the following conditions to search
a “data”.
1. Find the middle element of the array (i.e., n/2 is the middle element if the array or the sub-
array contains n elements).
2. Compare the middle element with the search element key, then there are following
three cases.
(a) If the middle element is the desired element, then search is successful.
(b) If it is less than desired data, then search only the first half of the array, i.e., the
elements which come to the left side of the middle element.
(c) If it is greater than the desired data, then search only the second half of the array, i.e.,
the elements which come to the right side of the middle element.
3. Repeat the same steps until an element are found or exhaust the search area.

Algorithm: Binary Search


Let A be an array of n elements. Let l and h are the lower and higher bounds of the array. Key is
the element to be searched. Then this algorithm will find the location “loc” of key in A.

Steps:
1. Start
2. Input an array A of n element.
3. Input Key value.
4. Initialize loc =0.
5. Repeat for i=0 to i<n
6. l=0, h=n-1,loc=0;
7. Repeat while(l<=h)
8. mid =(l+h)/2;
9. if(key==a[mid])
a. loc=mid;
b. break;
10. else if(key<a[mid]) h=mid-1;
11. else l=mid+1;
12. endif.
13. Endwhile
14. If (loc≠ 0) then
 Print “Key Element found in the list.”
15. Else

7
ZENEX DEGREE COLLEGE,

 Print “Key Element found in the list.


16. Stop

What are the Key differences between Linear Search and Binary

Search? Key Differences Between Linear Search and Binary Search

1. Linear search is iterative in nature and uses sequential approach. On the other hand,
Binary search implements divide and conquer approach.
2. The time complexity of linear search is O(N) while binary search has O(log2N).
3. The best case time in linear search is for the first element i.e., O(1). As against, in
binary search, it is for the middle element, i.e., O(1).
4. In the linear search, worst case for searching an element is N number of comparison.
In contrast, it is log2N number of comparison for binary search.
5. Linear search can be implemented in an array as well as in linked list whereas binary
search can not be implemented directly on linked list.
6. As we know Binary search requires the sorted array that is reason It requires
processing to insert at its proper place to maintain a sorted list. On the contrary
linear search does not require sorted elements, so elements are easily inserted at
the end of the list.
7. Linear search is easy to use, and there is no need for any ordered elements. On the
other hand, Binary search algorithm is however tricky, and elements are necessarily
arranged in order.

Important Questions:
1.What are the representations of Graphs in memory
explai? 2.Write about Depth First Search (DFS) Traversal?
3. Write about Breadth First Search (BFS) Traversal?
4. What are the algorithms to find minimal spanning Tree and explain?

Important Questions:
1. Write an algorithm for Booble Sort and analyze with an
example? 2.Write an algorithm for Merge Sort and analyze with an
example? 3.Write an algorithm for Quick Sort and analyze with an
example? 4.What is searching?Write about sequential or linear
search?
5.What are the Key differences between Linear Search and Binary Search?

You might also like