You are on page 1of 70

3 Semester Lab Manual

18MCA36: DBMS Lab


Program: 1
No town Records has decided to store information about musicians who perform on its albums. Each
musician that records at No town has an SSN, a name, an address, and a phone number. No musician has
more than one phone. Each instrument used in songs recorded at No town has a unique identification
number, a name (e.g., guitar, synthesizer, flute) and musical key (e.g., C, B-flat, E-flat). Each album
recorded on the No town label has a unique identification number, a title, a copyright date and a format
(e.g., CD or MC). Each song recorded at No town has a title and an author. Each musician may play
several instruments, and given instrument may be played by several musicians. Each album has a number
of songs on it, but no song may appear on more than one album. Each song is performed by one or more
musicians, and a musician may perform a number of songs. Each album has exactly one musician who
acts as its producer. A musician may produce several albums.
Queries
a) List musician name, title of the song which he has played, the album in which song has
occulted.
b) List the details of songs which are performed by more than 3 musicians.
c) List the different instruments played by the musicians and the average number of musicians
who play the instrument.
d) Retrieve album title produced by the producer who plays guitar as well as flute and has
produced no of songs greater than the average songs produced by all producers.
e) List the details of musicians who can play all the instruments present.

Relational schema:

MUSICIAN
Ssn Name Addrs Phone

PLAYS
Id Ssn

INSTRUMENT
Id Iname M_key

Dept. of MCA, The Oxford College of Engineering Page 1


3 Semester Lab Manual

PERFORMS
Ssn Title

SONG
Title Author Aid

ALBUM
Aid Title C_date Format Producer_ssn

create table musician(ssn number(3) primary key,name varchar(30),addr varchar(30),phone number(10)


unique);

create table instrument(id number(4) primary key,iname varchar(30),mkey varchar(10));

create table plays(ssn number(3) references musician(ssn),id number(4) references


instrument(id),primary key(ssn,id));

create table songs(title varchar (10) primary key, author varchar(20), aid number(4) references
album(aid));

create table performs(title varchar(10) references songs(title), ssn number(4) references


musician(ssn),primary key(title,ssn));

create table album(aid number(4) primary key, atitle varchar(30) unique,format varchar(5),
rdate date, ssn number(3) references musician(ssn));

Table Description:
desc musician
Name Null? Type
----------------------------------------- -------- ---------------------
SSN NOT NULL NUMBER(3)
NAME VARCHAR2(30)
ADDR VARCHAR2(30)
PHONE NUMBER(10)

desc instrument
Name Null? Type

----------------------------------------- -------- ---------------------


ID NOT NULL NUMBER(4)
INAME VARCHAR2(30)
MKEY VARCHAR2(10)

desc plays
Name Null? Type

Dept. of MCA, The Oxford College of Engineering Page 2


3 Semester Lab Manual
----------------------------------------- -------- ---------------------
SSN NOT NULL NUMBER(3)
ID NOT NULL NUMBER(4)

desc songs
Name Null? Type
----------------------------------------- -------- ---------------------
TITLE NOT NULL VARCHAR2(10)
AUTHOR VARCHAR2(20)
AID NUMBER(4)

desc album
Name Null? Type
----------------------------------------- -------- ---------------------
AID NOT NULL NUMBER(4)
ATITLE VARCHAR2(30)
FORMAT VARCHAR2(5)
RDATE DATE
SSN NUMBER(3)

desc performs
Name Null? Type
----------------------------------------- -------- ---------------------
TITLE NOT NULL VARCHAR2(10)
SSN NOT NULL NUMBER(4)

Values inside Tables:


select * from musician;

SSN NAME ADDR PHONE


---------- ------------- ------------- ----------------
123 rahman bangalore 9999999999
124 ilayaraja chennai 8888888888
125 pritam mumbai 7777777777
126 harris hyderbad 9999998888
127 jessi cochin 9844498444
select * from instrument;

ID INAME MKEY
---------- ------------------------------ ----------
1 guitar high
2 flute flat
3 violin low
4 drums rock
5 piano high
6 tabala low

select * from plays;

SSN ID
---------- ----------
123 1

Dept. of MCA, The Oxford College of Engineering Page 3


3 Semester Lab Manual
123 2
124 4
123 4
126 6
127 5
124 3
123 3
123 5
123 6

select * from songs;

TITLE AUTHOR AID


---------- -------------------- ----------
jaadu kiran 102
sri sai krishna 101
janam hari 101
sanam ram 104
stotra charan 103

select * from album;

AID ATITLE FORMA RDATE SSN


---------- ------------------------------ ----- --------- ----------
101 abc cd 12-MAR-99 123
102 xyz mp3 12-JUN-99 123
103 mno mp4 15-MAR-99 124
104 pqr tape 19-DEC-90 125
105 aaa cd 10-JAN-10 126
106 bbb cd 10-MAR-99 123
107 ccc tape 12-APR-93 123

select * from performs;

TITLE SSN
---------- ----------
jaadu 123
jaadu 124
sri sai 125
sanam 126
stotra 127
jaadu1 123

Queries:

query 1: select m.name , s.title , a.aid from musician m, performs p, songs s, album a where
m.ssn=p.ssn and p.title =s.title and s.aid=a.aid;

NAME TITLE AID


------------------------------ ---------- ----------
rahman jaadu 102
ilayaraja jaadu 102

Dept. of MCA, The Oxford College of Engineering Page 4


3 Semester Lab Manual
pritam sri sai 101
harris sanam 104
jessi stotra 103

query2: select title, author from songs where title=(select title from performs p group by title
having count(*)>3);

TITLE AUTHOR
---------- --------------------
jaadu kiran

query 3: select iname, (select count(ssn) from plays where id=i.id group by id) as No_of_musicians
from instrument I;

INAME NO_OF_MUSICIANS
------------------------------ ---------------
guitar 1
flute 1
violin 2
drums 2
piano 2
tabala 2

(or)

select distinct(i.iname),count(p.id) as Total_Musician, count(p.id)/(select count(*) from musician)


as Average_Musician from instrument i,play p where i.id=p.id group by Iname;

query 4: select atitle from album where ssn in


(select m.ssn from musician m where m.ssn
in (select ssn from instrument i, plays p where
p.id=i.id and iname in ('guitar','flute'))) and
ssn=(select ssn from album group by ssn having
count(ssn)= (select count(distinct ssn) from album));

ATITLE
-------
abc
xyz
www
sss

query 5: select * from musician where


M_id in ( select M_id from play group by M_id
having count(I_id)=(select count(I_id) from instrument));

Dept. of MCA, The Oxford College of Engineering Page 5


3 Semester Lab Manual
Program: 2
Professors have a PROFID, a name, an age, a rank, and a research specialty. Projects have a project
number, a sponsor name (e.g. UGC/AICTE/...), a starting date, an ending date, and a budget. Graduate
students have an USN, a name, an age, and a degree program (e.g. MCA/ MPhil/BE/ME ..). Each project
is managed exactly by one professor (known as the project's principal investigator). Each project is
worked on by one or more professors (known as the project's co-investigators). Professors can
manage/work on multiple projects. Each project is worked on by one or more graduate students (known
as the project's research assistants). Graduate students can work on multiple projects. Each professor can
supervise many students. A student who is working on a project can be supervised by only one professor.

Queries
a) Retrieve the names of all professors who do not have an ongoing project of more than 1
lakh.
b) Retrieve the names of all graduate students along with their professors under whom they
work and project sponsor.
c) List the professors and sum of the budget of their projects started after 2005 but ended in
2010.
d) List the names of professors who has a total worth of project greater than the average budget
of projects sanctioned
e) List the professors who work on all the projects.

ER DIAGRAM

Dept. of MCA, The Oxford College of Engineering Page 6


3 Semester Lab Manual

RELATIONAL SCHEMA

PROFESSOR
PROFID NAME AGE RANK RESEARCH

PROJECT
PNO SPONSOR SDATE BUDGET EDATE PROFID

STUDENT
USN SNAME AGE DEGREE PROFID

P_WORKSON
PROFID PNO

S_WORKSON

USN PNO

Table creation:
1) create table professor2(profid number(3) primary key ,name varchar(20),age number(3), rank
number(3), research varchar(20));
2) create table projects2 (pno number(3) primary key,sponsor varchar(10), sdate date, edate date,
budget number(5), p_investigator number(3) references professor(profid));
3) create table student2(usn number(5) primary key,sname varchar(20),age number(3),degree
varchar(10), profid number(3) references professor(profid));
4)create table pworkson(profid number(3) references professor(profid), pno number(3) references
projects(pno), primary key(profid,pno))
5)create table sworkson(usn number(5) references student(usn),pno number(3) references
projects(pno), primary key(usn,pno));

Table Description:

desc professor
Name Null? Type
----------------------------------------- -------- ---------------------
PROFID NOT NULL NUMBER(3)

Dept. of MCA, The Oxford College of Engineering Page 7


3 Semester Lab Manual
NAME VARCHAR2(20)
AGE NUMBER(3)
RANK NUMBER(3)
RESEARCH VARCHAR2(20)

desc projects
Name Null? Type
----------------------------------------- -------- ---------------------
PNO NOT NULL NUMBER(3)
SPONSOR VARCHAR2(10)
SDATE DATE
EDATE DATE
BUDGET NUMBER(5)
P_INVESTIGATOR NUMBER(3)

desc student
Name Null? Type
----------------------------------------- -------- ---------------------
USN NOT NULL NUMBER(5)
SNAME VARCHAR2(20)
AGE NUMBER(3)
DEGREE VARCHAR2(10)
PROFID NUMBER(3)

desc pworkson
Name Null? Type
----------------------------------------- -------- ---------------------
PROFID NOT NULL NUMBER(3)
PNO NOT NULL NUMBER(3)

desc sworkson
Name Null? Type
----------------------------------------- -------- ---------------------
USN NOT NULL NUMBER(5)
PNO NOT NULL NUMBER(3)

Values inside Tables:

select * from professor;

PROFID NAME AGE RANK RESEARCH


---------- -------------------- ---------- ---------- -------------------
1 hemanth 35 1 sp
2 vishwanath 35 1 os
3 r aghu 31 1 unix

Dept. of MCA, The Oxford College of Engineering Page 8


3 Semester Lab Manual
4 kumar 28 1 oops
5 basavaraju 28 1 oomd

select * from projects;

PNO SPONSOR SDATE EDATE BUDGET P_INVESTIGATOR


---------- ---------- --------- --------- ---------- --------------
111 vtu 12-JAN-12 12-JAN-2005 100000 1
222 govt 18-MAR-13 18-MAR-2004 400000 2
333 vtu 22-AUG-14 22-AUG-2005 600000 3
444 central 20-APR-14 20-APR-2010 75000 4
555 central 25-FEB-12 25-FEB-2006 90000 5

select * from student


USN SNAME AGE DEGREE PROFID
---------- -------------------- ---------- ---------- ----------
123 shashi 22 mca 1
124 rajath 21 mca 2
125 harish 21 be 3
126 ram 24 msc 4
127 kiran 22 mca 5

select * from pworkson;

PROFID PNO
---------- ----------
1 111
2 222
3 333
4 444
5 555
2 111
2 333
2 444
2 555

select * from sworkson;

USN PNO
---------- ----------
123 111
124 222
125 333
126 444
127 555

Dept. of MCA, The Oxford College of Engineering Page 9


3 Semester Lab Manual
Queries:
Query 1: ) Retrieve the names of all professors who do not have an ongoing project of more than 1 lakh.

select name from professor p , pworkson pw , projects pj where p.profid = pw.profid and
pw.pno=pj.pno and budget >100000;
NAME
--------------------
hemanth
raghu
kumar
basavaraju

query 2: ) Retrieve the names of all graduate students along with their professors under whom they work
and project sponsor.

select sname,name as "professor", sponsor from professor p ,student s , sworkson sw , projects pr


where p.profid=s.profid and s.usn=sw.usn and sw.pno=pr.pno

SNAME professor SPONSOR


-------------------- -------------------- ----------
shashi vishwanath vtu
rajath hemanth govt
harish raghu vtu
ram kumar central
kiran basavaraju central

Queries3: List the professors and sum of the budget of their projects started after 2005 but ended in 2010.

select name, (select sum(budget) from projects where p_investigator=p.profid group by


p_investigator) as "total budget" from professor p , projects where profid=p_investigator and
sdate like '%15' and edate like '%10'

(or)
select pf.name,sum(pj.budget) as Total_budget from work_prof wp, professor pf, project pj where
pf.profid = wp.rofidid and pj.pno=wp.pno and EXTRACT(YEAR FROM sdate)>2005 and
EXTRACT(YEAR FROM edate)=2010 group by pf.name;

NAME total budget


-------------------- ------------
vishwanath 120000
basavaraju 90000

query4: List the names of professors who has a total worth of project greater than the average budget of
projects sanctioned

select name from professor ,projects where profid= p_investigator and budget>(select avg(budget)
from projects)
NAME

Dept. of MCA, The Oxford College of Engineering Page 10


3 Semester Lab Manual
----------------
vishwanath
basavaraju

query5: ) List the professors who work on all the projects.

select name from professor where profid=(select p.profid from pworkson p group by p.profid
having count(p.profid)=(select count(pno) from projects))
NAME
------------------
hemanth
Program: 3

A bank has many branches and a large number of customers. Bank is identified by its code.Other details
like name, address and phone for each bank are also stored. Each branch isidentified by its bank. Branch
has name, address and phone. A customer can open differentkinds of accounts with the branches. An
account can belong to more than one customer.Customers are identified by their SSN, name, address and
phone number. Age is used as afactor to check whether customer is a major. There are different types of
loans, each identifiedby a loan number. A customer can take more than one type of loan and a loan can
be given tomore than one customer. Loans have a duration and interest rate. Make suitable
assumptionsand use them in showing maximum and minimum cardinality ratios.

Queries:
a) List the details of customers who have joint account and also have at least one loan.
b) List the details of the branch which has given maximum loan.
c) List the details of saving accounts opened in the SBI branches located at Bangalore.
d) List the name of branch along with its bank name and total amount of loan given by it.
e) Retrieve the names of customers who have accounts in all the branches located in a specific city

ER diagram:

Dept. of MCA, The Oxford College of Engineering Page 11


3 Semester Lab Manual

Create Table Query


1) SQL> create table bank(
bank_code varchar2(10) primary key,
bank_name varchar2(20),
bank_address varchar2(25),
phone number(10));
2) SQL> create table branch(
branch_name varchar2(20) primary key,
city varchar2(25), phone number(10),
bank_code varchar2(10) references bank(bank_code));

3) SQL> create table customer(


ssn number(9) primary key,
cust_name varchar2(25),
cust_address varchar2(25), cust_phone number(10),
age number(2) check(age >18));
4) SQL> create table account(
account_no number(10) primary key,
account_type varchar2(10),
account_access varchar(10),
amount number(10,2),
branch_name varchar2(20) references branch(branch_name));
5) SQL> create table depositor(
account_no number(10) references account(account_no),
ssn number(9) references customer(ssn));
6) SQL> create table loan(
loan_no number(10) primary key,
duration number(10),
Dept. of MCA, The Oxford College of Engineering Page 12
3 Semester Lab Manual
interest_rate number(10),
loan_amount number(10,2),
branch_name varchar2(20) references branch(branch_name));
7) SQL> create table borrower(
ssn number(10) references customer(ssn),
loan_no number(10) references loan(loan_no));
Insert Into
1) SQL> insert into bank values ('SBI','StateBankOfIndia','CorporationCircle,Delhi',86342189);

1 Row Created.
2) SQL> insert into branch values ('SBIJayanagar','JayaNagar,Bangalore',78945612,'SBI');

1 Row Created.
3) SQL> insert into customer values(852147963,'Vasanth','Jayanagar',85223147,35);

1 Row Created.
4) SQL> insert into account values(456456,'savings','single',50000,'SBIT.Nagar');

1 Row Created.
5) SQL> insert into depositor values (456456,357869142);

1 Row Created.
6) SQL> insert into loan values(123456,20,10,1000000,'SBIJayanagar');

1 Row Created.
7) SQL> insert into borrower values(852147987,123459);

1 Row Created.
Tables
BANK Table

BRANCH Table

CUSTOMER Table

Dept. of MCA, The Oxford College of Engineering Page 13


3 Semester Lab Manual

ACCOUNT Table

DEPOSITOR Table

LOAN Table

BORROWER Table

Queries
a) List the details of customers who have joint account and also have at least one loan.

SQL> select * from customer where ssn in


(select ssn from depositor where account_no in
(select account_no from account where account_access = 'joint') intersect
select ssn from borrower);

Dept. of MCA, The Oxford College of Engineering Page 14


3 Semester Lab Manual

b) List the details of the branch which has given maximum loan.

SQL> select * from branch where branch_name in


(select branch_name from (select branch_name, sum(loan_amount) l_amt
from loan group by branch_name) where
l_amt in (select max(sum(loan_amount)) from loan
group by branch_name));

c) List the details of saving accounts opened in the SBI branches located at Bangalore.
SQL> select * from account where account_type = 'savings' and
branch_name in (select branch_name from branch where city
like '%Bangalore%' and branch_name like 'SBI%');

d) List the name of branch along with its bank name and total amount of loan given by it.
SQL> select distinct b.bank_name, br.branch_name, l.loan_amt from
bank b, branch br , loan l, (select branch_name,sum(loan_amount)
from loan group by branch_name) where b.bank_code = br.bank_code
and br.branch_name = l.branch_name;

e) Retrieve the names of customers who have accounts in all the branches located in a specific
city.

SQL> select cust_name from customer where ssn in ( select ssn from depositor where
account_no in (select account_no from account where (branch_name) in (select branch_name
from branch where city='bangalore' group by (branch_name))));

Program 4
Patients are identified by an SSN, and their names, addresses, and ages must be recorded.Doctors are
identified by an SSN. For each doctor, the name, specialty, and years of experiencemust be recorded.
Each pharmaceutical company is identified by name; it has an address andone phone number. For each
Dept. of MCA, The Oxford College of Engineering Page 15
3 Semester Lab Manual
drug, the trade name and formula must be recorded. Each drug issold by a given pharmaceutical
company, and the trade name identifies a drug uniquely fromamong the products of that company. Each
pharmacy has a name, address, and phone number.Each patient is checked up by some doctor. Every
doctor has at least one patient. Eachpharmacy sells several drugs and has a price for each. A drug could
be sold at severalpharmacies, and the price could vary from one pharmacy to another. Doctors prescribe
drugs forpatients. A doctor could prescribe one or more drugs for several patients, and a patient
couldobtain prescriptions from several doctors. Each prescription has a date and a quantity
associatedwith it. Pharmaceutical companies have long-term contracts with pharmacies. A
pharmaceuticalcompany can contract with several pharmacies, and a pharmacy can contract with
severalpharmaceutical companies. For each contract, you have to store a start date, an end date,supervisor
and the text of the contract.

Queries:
a) List the details of patients who are 20 years old and have been checked by eye-specialist.
b) List the details of doctors who have given the prescription to more than 20 patients in year
2013.
c) List the details of pharmaceutical companies who supply drug to more than 10 pharmacies in
the same city where company is located.
d) List the details of drug supplied by only one pharmaceutical company.
e) List the details of drug supplied by all pharmaceutical companies

ER & Relation Schema:

Dept. of MCA, The Oxford College of Engineering Page 16


3 Semester Lab Manual

TABLE CREATION

Create table patient


(ssn number(3) primary key,
Name varchar(20),
Addr varchar(30),

Dept. of MCA, The Oxford College of Engineering Page 17


3 Semester Lab Manual
Age number(3));

Create table doctor


(ssn number(3) primary key,
Name varchar(20),
Addr varchar(30),
Speciality varchar(30),
Experience number(3));

Create table pharma_company


(name varchar(20) primary key,
Addr varchar(20),
Phone number(10));

Create table pharmacy


(pname varchar(20) primary key,
Addr varchar(30),
Phone number(10));

Create table drug


(tname varchar(20) primary key,
Formula varchar(20));

Create table docpatient


(pssn number(3) references patient,
Dssc number(3) references doctor,
Primary key(pssn,dssn));

create table pcomp_drug(tname varchar(20) references drug,


name varchar(20) references PHARMA_COMPANY,
primary key(tname,name));

create table pharma_contract


(name varchar(20) references pharma_company,
phname varchar(20) references PHARMACY,
sdate date,
edate date,
supervisor varchar(30),
text varchar(30));

create table pharmacy_drug


(phname varchar(20) references PHARMACY,
tname varchar(2) references drug,
primary key(phname,tname));

create table prescription


(pssn number(3) references patient,
dssn number(3) references doctor,
tname varchar(2) references drug,
qty number(3),
pdate date);

Dept. of MCA, The Oxford College of Engineering Page 18


3 Semester Lab Manual
select * from patient;

SSN NAME ADDR AGE


---------- -------------------- -------------------- ----------
1 harish bangalore 28
2 raj mysore 55
3 thomas delhi 55
4 kishan bangalore 34
5 ram mangalore 76

select * from doctor;

DSSN NAME SPECIALITY EXPERIENCE


---------- -------------------- -------------------- ----------
123 nagesh eye 8
124 raghu ortho 8
125 hemanth surgeon 12
126 vishwanath physician 15
127 kumar skin 5

select * from drug;

TRNAME FORMULA
--------------- ----------
saridon abc
anacin xyz
crocin www
dolopar ggg
cpm qqq

select * from pharmacy;

PHNAME ADDR PHONE


-------------------- -------------------- ----------
medplus rr nagar 87766565
apollo bangalore 90987655
sai mysore 987668877
maruthi bangalore 967565697
ganesh bangalore 89876566

select * from pharma_company;

NAME ADDR PHONE


-------------------- -------------------- ----------
cipla bangalore 97765545
ranbaxy delhi 986568799
drreddy bangalore 977654689
himalaya bangalore 985754687
johnson delhi 966555678

select * from prescription;

Dept. of MCA, The Oxford College of Engineering Page 19


3 Semester Lab Manual
PSSN DSSN TNAME QTY PDATE
---------- ---------- -------------------- ---------- ---------
1 123 saridon 5 12-MAR-12
2 124 crocin 8 15-MAR-13
3 125 cpm 8 10-JUL-14
4 126 dolopar 12 10-MAY-13
5 127 crocin 7 16-JAN-13

select * from pcomp_drug;

TNAME NAME
---------------- --------------------
saridon cipla
anacin cipla
crocin himalaya
dolopar ranbaxy

select * from pharmacy_drug;

PHNAME TNAME
---------------- --------------------
medplus dolopar
apollo crocin
apollo saridon
sai crocin
ganesh cpm

select * from pharma_contract;

NAME PHNAME SDATE EDATE SUPERVISOR TEXT


---------- ------------ ------ --------- --------- ------------------ ----------
cipla medplus 12-JAN-77 12-MAR-16 abc ssss
ranbaxy apollo 12-JUN-14 12-JUN-17 aaa rrr
himalaya sai 12-JUL-12 12-JUN-16 fas eeee
drreddy ganesh 12-MAY-13 22-MAR-14 fgf ttt

select * from docpatient;

DSSN PSSN
---------- ----------
123 1
123 2
124 1
125 3
126 4
127 5

Queries:

1) select * from patient where age=28 and ssn in(select pssn from docpatient where dssn in (select dssn
from doctor where SPECIALITY='eye'))

Dept. of MCA, The Oxford College of Engineering Page 20


3 Semester Lab Manual

SSN NAME ADDR AGE


----- -------------------- -------------------- ----------
1 harish bangalore 28

2) select * from doctor where dssn in (select dssn from prescription where pdate like '%13' group by dssn
having count(pssn)>=2);

DSSN NAME SPECIALITY EXPERIENCE


----- -------------------- -------------------- ----------
124 raghu eye 8

3) select * from pharma_company where name in (select name from pharma_contract where phname in (
select phname from pharmacy where pharma_company.addr=pharmacy.addr) group by name having
count(phname)>=2);

NAME ADDR PHONE


-------------------- -------------------- ----------
drreddy bangalore 977654689

4) select * from drug where trname in (select tname from pcomp_drug where name='cipla');

TRNAME FORMULA
-------------------- ---------
anacin xyz
saridon abc

5) select * from drug where trname in (select distinct tname from pcomp_drug);

TRNAME FORMULA
-------------------- --------
anacin xyz
crocin www
dolopar ggg
saridon abc

Program: 5
Data requirements of movie industry are captured. Each movie is identified by title andyear of release.
Each movie has length in minutes and classified under one genres (like action,horror etc.). Each movie
has a plot outline. Production companies are identified by name andeach has an address. A production
company produces one or more movies. Actors are identifiedby id. Other details likename and date of
birth of actors are also stored. Each actor acts in oneor more movies. Each actor has a role in movie.
Directors are identified by id. Other details likename and date of birth of directors are also stored. Each
director directs one or more movies.Each movie has one or more actors and one or more directors and is
produced by a productioncompany.

Queries:
a) List the details of horror movies released in 2012 and directed by more than 2 directors.
b) List the details of actors who acted in movies having same titles but released before 2000
and after 2010.
c) List the details of production companies producing maximum movies.
d) List the details of movies where director and actor have same date of birth.

Dept. of MCA, The Oxford College of Engineering Page 21


3 Semester Lab Manual
e) Retrieve the names of directors directed all the movies produced by any one production
company.

ER and Relationa schema

Dept. of MCA, The Oxford College of Engineering Page 22


3 Semester Lab Manual
CREATION OF TABLES:

create table production


(pc_name varchar2(15) primary key,
pc_address varchar2(15));

create table movie


(m_title varchar2(15) ,
m_length number(3),
m_yor number(4),
m_genres varchar2(10),
outline varchar2(15),
m_pcname references production ,
primary key(m_title,m_yor));

create table actors


(a_id number(5) primary key,
a_name varchar2(15),
a_dob date);

create table directors


(d_id number(5) number(5) primary key,
d_name varchar2(15),
d_dob date);

create table moviedirectors


(m_title varchar(15) ,
m_yor number(4) ,
foreign key (m_title,m_yor) references movie,
d_id number(5) references directors,
primary key(m_title,m_yor,md_id));

create table movieactors


(m_title varchar(15),
m_yor number(4),
ma_id number(5) references actors,
role varchar2(15),
foreign key(m_title, m_yor) references movie,
primary key(m_title,m_yor,ma_id));

desc movie;
Name Null? Type
----------------------------------------- -------- ---------------------------
M_TITLE NOT NULL VARCHAR2(15)
M_LENGTH NUMBER(3)
M_YOR NOT NULL NUMBER(4)
M_GENRES VARCHAR2(10)
OUTLINE VARCHAR2(15)
M_PCNAME VARCHAR2(15)

desc actors;
Name Null? Type
----------------------------------------- -------- ---------------------------
A_ID NOT NULL NUMBER(5)

Dept. of MCA, The Oxford College of Engineering Page 23


3 Semester Lab Manual
A_NAME VARCHAR2(15)
A_DOB DATE

desc directors;
Name Null? Type
----------------------------------------- -------- ---------------------------
D_ID NOT NULL NUMBER(5)
D_NAME VARCHAR2(15)
D_DOB DATE

desc production;
Name Null? Type
----------------------------------------- -------- ---------------------------
PC_NAME NOT NULL VARCHAR2(15)
PC_ADDRESS VARCHAR2(15)

desc moviedirectors;
Name Null? Type
----------------------------------------- -------- ---------------------------
M_TITLE NOT NULL VARCHAR2(15)
M_YOR NOT NULL NUMBER(4)
MD_ID NOT NULL NUMBER(5)

desc movieactors;
Name Null? Type
----------------------------------------- -------- ---------------------------
M_TITLE NOT NULL VARCHAR2(15)
M_YOR NOT NULL NUMBER(4)
A_ID NOT NULL NUMBER(5)
ROLE VARCHAR2(15)

select * from production;

PC_NAME PC_ADDRESS
--------------- ---------------
avm chennai
yashraj bangalore
sun bangalore
rockline bangalore
ram mumbai

select * from movie;

M_TITLE M_LENGTH M_YOR M_GENRES OUTLINE M_PCNAME


--------------- ---------- ---------- ---------- --------------- ---------------
ddlj 2 1996 romantic love avm
srikrishna 3 2010 myth devotion sun
krish 2 2014 animated cartoon yashraj
chennaexp 2 2013 drama comedy rockline
robo 3 2012 horror comedy ram
ddlj 2 2012 horror love avm
sur 2 2012 romantic love avm

Dept. of MCA, The Oxford College of Engineering Page 24


3 Semester Lab Manual
select * from actors;

A_ID A_NAME A_DOB


---------- --------------- ---------
111 amitabh 10-MAR-55
222 shahrukh 15-MAR-77
333 hrithik 15-JAN-99
444 akshay 13-APR-75
555 amir 15-JAN-76

select * from directors;

D_ID D_NAME D_DOB


---------- --------------- ---------
1 abc 12-MAR-77
2 x yz 22-MAR-88
3 mno 15-JAN-99
4 pqr 15-JUL-89
5 jkl 25-FEB-85

select * from moviedirectors;

M_TITLE M_YOR MD_ID


--------------- ---------- ----------
ddlj 1996 1
srikrishna 2010 2
krish 2014 3
chennaexp 2013 4
robo 2012 5
rrobo 2012 3

select * from movieactors

M_TITLE M_YOR A_ID ROLE


--------------- ---------- ---------- ---------------
ddlj 1996 111 hero
krish 2014 333 hero
chennaexp 2013 222 hero
robo 2012 444 hero
srikrishna 2010 555 hero
ddlj 2012 111 h ero

query1:

select * from movie where m_yor='2012'and m_genres='horror' and m_title in


(select m_title from moviedirectors group by m_title having count(*)>=2);

M_TITLE M_LENGTH M_YOR M_GENRES OUTLINE M_PCNAME


--------------- ---------- ---------- ---------- --------------- ------------
robo 3 2012 horror comedy ram

Dept. of MCA, The Oxford College of Engineering Page 25


3 Semester Lab Manual
query2:

select * from actors where A_ID in (select m.A_ID from movieactors m,


movieactors n where m.m_title=n.m_title and m.m_yor<2000 and n.m_yor >2010);

A_ID A_NAME A_DOB


----- --------------- ---------
111 amitabh 10-MAR-55

query3:

select * from production where PC_NAME in


(select M_PCNAME from movie group by m_pcname having count(m_pcname)
>=(select max(count(m_pcname)) from movie group by m_pcname));

PC_NAME PC_ADDRESS
--------------- --------------
avm Chennai

query4:

select * from movie where m_title in


(select m_title from moviedirectors where m_title in
(select m_title from movieactors where a_id in
(select a_id from actors a, directors d where a.a_dob=d.d_dob)));

M_TITLE M_LENGTH M_YOR M_GENRES OUTLINE M_PCNAME

--------------- ---------- ---------- ---------- --------------- ---------


krish 2 2014 animated cartoon yashraj

query5:

select d_name from directors where d_id in


(select md_id from moviedirectors where (m_title,m_yor) in
(select m_title,m_yor from movie where M_PCNAME='avm'));

D_NAME
----------
abc

Dept. of MCA, The Oxford College of Engineering Page 26


3 Semester Lab Manual

18MCA37: Python Programming Lab

1. Write a program to sum all the elements from n1 to n2 where n1 and n2


are positive integers.
n1 = int(input("enter starting number:"))
n2 = int(input("enter ending number:"))
if n1 > n2: n1, n2 = n2, n1
sum = 0
for i in range(n1, n2+1, 1):
sum = sum + i
print(i)

print "Sum of number between: ",n1,"&",n2,"is:",sum

2. Input an array of n numbers and find separately the sum of positive


numbers and negative numbers.

n=int(input("Enter how many number: "))


print "Enter", n , "numbers: "
Sumnegv = Sumposv = 0
num = []
for i in range(0, n):
num.append(int(input()))
for i in range(0, n):
if(num[i] <0):
Sumnegv += num[i]
else:
Sumposv += num[i]
print "Sum of Positive numbers is: ", Sumposv
print "Sum of Negative numbers is: ", Sumnegv

Dept. of MCA, The Oxford College of Engineering Page 27


3 Semester Lab Manual

3. Write a program to search an element using linear search.


n=int(input("Enter how many number: "))
print "Enter", n , "numbers: "
num = []
for i in range(0, n):
num.append(int(input()))
Sitem=int(input("Enter the search item: "))
found=False
for i in range(0, n):
if(num[i] == Sitem):
found=True
break
if (found == True):
print "Element found at position", i+1
else:
print "Element not found"

4. Write a program to search an element using binary search.

def binarySearch(alist, item):


first = 0
last = len(alist)-1
found = False

while first<=last and not found:


midpoint = (first + last)//2
if alist[midpoint] == item:
return midpoint
else:
if item < alist[midpoint]:
last = midpoint-1
else:
first = midpoint+1
return -1

n=int(input("Enter how many number: "))


print "Enter", n , "numbers: "
Dept. of MCA, The Oxford College of Engineering Page 28
3 Semester Lab Manual

num = []
for i in range(0, n):
num.append(int(input()))
num.sort()
print "the sorted elements are:"
print(num)
Sitem=int(input("Enter the search item: "))
posin = binarySearch(num, Sitem)
if (posin == -1):
print "Element not found "
else:
print "Element found at position", posin+1

5. Write a program to simulate stack.


import sys
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
if(self.isEmpty()):
print("Stack is empty : underflow condition")
return
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def display(self):
print(self.items)

Dept. of MCA, The Oxford College of Engineering Page 29


3 Semester Lab Manual

s=Stack()
while (True):
print("1. Push ")
print("2. Pop ")
print("3. Display")
print("4. Peek")
print("5. Display Size")
print("6. Is Empty")
print("7. Exit")
opn = int(input("Enter your option : "))
if (opn == 1):
item = input("Enter an item to push :")
s.push(item)
elif (opn == 2):
print(s.pop())
elif (opn == 3):
s.display()
elif (opn == 4):
print(s.peek())
elif (opn == 5):
print(s.size())
elif (opn == 6):
print(s.isEmpty())
else:
print("Program ends")
sys.exit()

Dept. of MCA, The Oxford College of Engineering Page 30


3 Semester Lab Manual

6. Using a stack evaluate an arithmetic expression.


def Infix(expr):
expr = list(expr)
stack = list()
num = ""
while len(expr) > 0:
c = expr.pop(0)
if c in "0123456789.":
num += c
else:
if num != "":
stack.append(num)
num = ""
if c in "+-*/":
stack.append(c)
elif c == ")":
num2 = stack.pop()
op = stack.pop()
num1 = stack.pop()
if op == "+":
stack.append(str(float(num1) + float(num2)))
elif op == "-":
stack.append(str(float(num1) - float(num2)))
elif op == "*":
stack.append(str(float(num1) * float(num2)))
elif op == "/":
stack.append(str(float(num1) / float(num2)))
return stack.pop()

expr = "(5+6)*4"
print expr
print Infix(expr), eval(expr)

7. Write a program to multiply two matrices.


# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]

Dept. of MCA, The Oxford College of Engineering Page 31


3 Semester Lab Manual

# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

8. Write a program to find the roots of a quadratic equation.


import math

class Error(Exception):
"""Base class for other exceptions"""
pass
class ImaginaryRootsError(Error):
print("Roots are imaginary")
"""Raised when the input value is too large"""
pass

# To take coefficient input from the users


a = int(input('Enter a: '))
b = int(input('Enter b: '))
c = int(input('Enter c: '))

# calculate the discriminant


try:
d = (b**2) - (4*a*c)
if(d<0):
raise ImaginaryRootsError

# find two solutions

Dept. of MCA, The Oxford College of Engineering Page 32


3 Semester Lab Manual

sol1 = (-b- math.sqrt(d))/(2*a)


sol2 = (-b+ math.sqrt(d))/(2*a)
except ArithmeticError as err:
print("Invalid operation", err)
except ImaginaryRootsError:
print("Imaginary Roots")
else:
print("The solution are {0} and {1}".format(sol1, sol2))

9. Insert a number in a sorted array.


def slist_insert(a, i):
b = []
len1 = len(a)
for x in range(0, len1):
if(int(a[x]) <= i):
b.append(a[x])
else:
break
b.append(i)
len2 = len(b)
for x in range(len2, len1):
b.append(a[x])
return b;
a = [1,1,2,4,7,7,11,13,13,13,15,20,25,26,27,30,45,70]
print("Array before insert", a)
i = int(input("Enter a number "))
a.append(i)
a.sort()
print("Array after insert", a)
print("Array after insert", slist_insert(a,i))

Dept. of MCA, The Oxford College of Engineering Page 33


3 Semester Lab Manual

10. Write a Python Program to check whether the given string is palindrome
or not using built in string manipulation methods.

def revstr(istr):
rstr =""
for x in range(len(istr)-1, -1, -1):
rstr = rstr + istr[x]
print(rstr)
return rstr
str1= raw_input("Enter a string: ")
#rstr = str1[::-1] #builtin string manipulator
rstr = revstr(str1) #user defined function
if(str1 == rstr):
print("String is a palindrome")
else:
print("String is not a palindrome")

11. Write a Python Program to read a word and prints the number of letters,
vowels and percentage of vowels in the word using dictionary.
dicty = {'vowels': 0, 'letters': 0, 'perVowels': 0}
word = raw_input("Enter a word")
for x in word:
dicty['letters'] += 1
if(x == 'a' or x == 'e' or x == 'i' or x == 'o' or x == 'u' or
x == 'A' or x == 'E' or x == 'I' or x == 'O' or x == 'U'):
dicty['vowels'] += 1
dicty['perVowels'] = (dicty['vowels'] * 100 // dicty['letters'])
print "Number of vowels in the word is ", dicty['vowels']
print "Number of letters in the word is ", dicty['letters']
print "Percentage of vowels in the word is ",dicty['perVowels']

Dept. of MCA, The Oxford College of Engineering Page 34


3 Semester Lab Manual

12. Write a Python Program to check a given sentence is a pangram or not


using function/Module.

def checkPangram(s):
List = []
# create list of 26 characters and set false each entry
for i in range(26):
List.append(False)

#converting the sentence to lowercase and iterating


# over the sentence
for c in s.lower():
if not c == " ":
# make the corresponding entry True
List[ord(c) -ord('a')]=True

#check if any character is missing then return False


for ch in List:
if ch == False:
return False
return True

# Driver Program to test above functions


sentence = "The quick brown fox jumps over the lazy dog"

if (checkPangram(sentence)):
print "\'", sentence," \'", "is a pangram"
else:
print "\'", sentence," \'", "is NOT a pangram"

13. Write a Python Event driven Program for file operations Press 1: to open
file in read mode 2: open the file in write mode 3: current position of the file
pointer #4: Reposition the pointer at the beginning 5: exit.
import sys
while(True):
print("1. Open file in read mode")
print("2. Open file in write mode")
print("3. Current postion of the file pointer")
print("4. Reposition the pointer at the beginning")
print("5. Exit")
opn = raw_input("Enter your option : ")

Dept. of MCA, The Oxford College of Engineering Page 35


3 Semester Lab Manual

if (opn == '1'):
fo = open("foo.txt", "r")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "File contents : ", fo.read()
fo.close()
if (opn == '2'):
fo = open("foo.txt", "w")
str1 = raw_input("Enter the string : ")
fo.write(str1)
fo.close()
if (opn == '3'):
fo = open("foo.txt", "r")
print "File pointer Position before read()", fo.tell()
print "File contents : ", fo.read()
print "File pointer Position after read()", fo.tell()
fo.close()
if (opn == '4'):
fo = open("foo.txt", "a+")
print "File pointer Position after open()", fo.tell()
pos = fo.seek(0, 0);
print "Now, File pointer Position after seek(0,0)", fo.tell()
str1 = raw_input("Enter some more contents for the file :")
fo.write(str1)
print "Now, File pointer Position after write()", fo.tell()
fo.close()
if (opn == '5'):
sys.exit()

Dept. of MCA, The Oxford College of Engineering Page 36


3 Semester Lab Manual

14. Write an Object oriented Python program to create two Time objects:
currentTime, which contains the current time; and breadTime, which
contains the amount of time it takes for a bread maker to make bread. Then
we'll use addTime to figure out when the bread will be done. Write the
printTime function to display the time when the bread will be done by the
bread maker.

class Time:
def printTime(self, time):
print str(time.hours), ":" , str(time.minutes), ":", str(time.seconds)

def addTime(t1, t2):


sum = Time()
sum.hours = t1.hours + t2.hours
sum.minutes = t1.minutes + t2.minutes
sum.seconds = t1.seconds + t2.seconds

if sum.seconds >= 60:


sum.seconds = sum.seconds - 60
sum.minutes = sum.minutes + 1

if sum.minutes >= 60:


sum.minutes = sum.minutes - 60
sum.hours = sum.hours + 1
return sum

currentTime = Time()
currentTime.hours = 9
currentTime.minutes = 14
currentTime.seconds = 30

breadTime = Time()
breadTime.hours = 3
breadTime.minutes = 35
breadTime.seconds = 40

doneTime = addTime(currentTime, breadTime)


doneTime.printTime(doneTime)

Dept. of MCA, The Oxford College of Engineering Page 37


3 Semester Lab Manual
16MCA38: ANALYSIS AND DESIGN OF ALGORITHMS
1. Implement Recursive Binary search and Linear search and determine the time required to
search an element. Repeat the experiment for different values of n, the number of elements in the
list to be searched and plot a graph of the time taken versus n.

Algorithm:
Algorithm linearsearch(a,l,n,x)
// input : a[l:n] of sorted elements, x=> search key
For i->0 to n-1
if(a[i]=x)
return i
end if
end for
return -1

Algorithm: Binarysearch (a,l,n,x)


// input : a[l:n] of sorted elements, x=> search key
if(l==n)
if(x==a[l])
return l;
else
return -1;
else
{
mid=(l+n)/2;
if(x=a[mid]) return mid;
else if(x<a[mid])
return binarysearch(a,l,mid-1,x);
else
return binarysearch(a,mid+1,n,x);
}

Program
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#include<time.h>
int linsearch(int [],int,int);
int binsearch(int [],int,int,int);
void genrand(int [],int);
void disp(int [],int);
void sort(int [],int);
int main(void)
{
int arr[500],n,key,i,pos=0,ch;
struct timeval tv;
double st,end;
system("clear");

do
{
printf("\n1. Linear Search");
printf("\n2. Binary Search");
printf("\n3. Exit");

Dept. of MCA, The Oxford College of Engineering Page 38


3 Semester Lab Manual
scanf("%d",&ch);
switch(ch)
{
case 1:

printf("\nEnter size of the Array");


scanf("%d",&n);
genrand(arr,n);
disp(arr,n);
printf("\nEnter element to search");
scanf("%d",&key);
gettimeofday(&tv,NULL);
st=tv.tv_sec+(tv.tv_usec/1000000.0);
pos=linsearch(arr,key,n);
if(pos==-1)
printf("\n%d not found",key);
else
printf("\n%d found at %d",key, pos);
gettimeofday(&tv,NULL);
end=tv.tv_sec+(tv.tv_usec/1000000.0);
printf("\nTime taken %.6lf", end-st);
break;
case 2:
printf("\nEnter size of the Array");
scanf("%d",&n);
genrand(arr,n);
sort(arr,n);
disp(arr,n);
printf("\nEnter element to search");
scanf("%d",&key);
gettimeofday(&tv,NULL);
st=tv.tv_sec+(tv.tv_usec/1000000.0);
pos=binsearch(arr,key,0,n-1);
if(pos==-1)
printf("\n%d not found",key);
else
printf("\n%d found at %d",key, pos+1);
gettimeofday(&tv,NULL);
end=tv.tv_sec+(tv.tv_usec/1000000.0);
printf("\nTime taken %.6lf", end-st);
break;
}
}while(ch!=3);
return 0;
}
void disp(int x[],int n)
{
int i;
for(i=0;i<n;i++)
printf("\t%d",x[i]);
}
void genrand(int x[],int n)
{
int i;

Dept. of MCA, The Oxford College of Engineering Page 39


3 Semester Lab Manual
srand(time(NULL));
for(i=0;i<n;i++)
x[i]=rand()%1000;
}
void sort(int a[],int n)
{
int i,j,t;
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(a[i] > a[j])
{
t=a[i];a[i]=a[j];a[j]=t;
}
}
int linsearch(int a[],int k,int n)
{
if(n==0)
return -1;
else if(k == a[n-1])
return n;
else
return linsearch(a,k,n-1);
}
int binsearch(int arr[],int k,int l,int h)
{
int m;
if(l <= h)
{
m=(l+h)/2;
if(k==arr[m])
return m;
if(k <arr[m])
return binsearch(arr,k,l,m-1);
if(k >arr[m])
return binsearch(arr,k,m+1,h);
}
else
return -1;
}

OUTPUT

N- Values Linear Search Binary Search Location


100 0.000018 0.000017 1
200 0.000026 0.000017 middle
300 0.000017 0.000018 last
400 0.000016 0.000017 random
500 0.000017 0.000016

Dept. of MCA, The Oxford College of Engineering Page 40


3 Semester Lab Manual
2. Sort a given set of elements using the Insertion Sort method and determine the time required to
sort the elements. Repeat the experiment for different values of n, the number of elements in the
list to be sorted and plot a graph of the time taken versus n.

Algorithm:

HEAPSORT(A)
BUILD-HEAP(A)
fori-> length[A] downto 2
do exchange A[1] <->A[i]
heap-size[A] <- heap-size[A] -1
HEAPIFY(A, 1)
BUILD-HEAP(A)
heap-size[A] <- length[A]
fori<- length[A]/2 downto 1
do HEAPIFY(A, i)

HEAPIFY(A, i)
l<- LEFT(i)
r<- RIGHT(i)
ifl<= heap-size[A] and A[l] >A[i]
then largest <- l
elselargest<- i
ifr<= heap-size[A] and A[r] >A[largest]
thenlargest<- r
iflargest != i
then exchange A[i] <- A[largest]
HEAPIFY(A,largest)

Program
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j] in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;

Dept. of MCA, The Oxford College of Engineering Page 41


3 Semester Lab Manual
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}

OUTPUT
Enter number of terms(should be less than 100): 5
Enter elements: 12
1
2
5
3
In ascending order: 1 2 3 5 12

Time taken to sort 0.000004

N- Values Time in Sec


10 0.000004
20 0.000006
30 0.000008
40 0.00001
50 0.000012

3. Sort a given set of elements using Merge sort method and determine the time required to sort the
elements. Repeat the experiment for different values of n, the number of elements in the list to be
sorted and plot a graph of the time taken versus n.

Algorithm Merge_Sort(A,low,high)
//given an array A of size n (high-low+1). This algorithm sorts elements in ascending order.
// the variables low and high are used to identify the position of first and last element in each partition.
Step1: if(low<high)
Step2: mid=(low+high)/2
Step3: call Merge_Sort(A,low,mid)
Step4: call Merge_Sort(A,mid+1,high)
Step5: call Merge(A,low,mid,high)
[end if]
Step 6: exit
Program
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
void fnGenRandInput(int [], int);
void fnDispArray( int [], int);

Dept. of MCA, The Oxford College of Engineering Page 42


3 Semester Lab Manual
void fnMerge(int [], int ,int ,int);
void fnMergeSort(int [], int , int);
int main()
{
struct timeval tv;
double dStart,dEnd;
int iaArr[100], iNum;
system("clear");
printf("\nEnter the number of elements to sort\n");
scanf("%d",&iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(iaArr,iNum);
fnDispArray(iaArr,iNum);
gettimeofday(&tv,NULL);
dStart = tv.tv_sec + (tv.tv_usec/1000000.0);
fnMergeSort(iaArr,0,iNum-1);
gettimeofday(&tv,NULL);
dEnd = tv.tv_sec + (tv.tv_usec/1000000.0);
printf("Time taken %.6lf\n",dEnd-dStart);
printf("\nSorted Array\n");
fnDispArray(iaArr,iNum);
return 0;
}
void fnMerge(int a[], int low, int mid, int high)
{
int i,k,j,b[100];
i=k=low;
j=mid+1;
while(i<=mid && j<=high)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(i<=mid)
b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(i=low;i<k;i++)
a[i]=b[i];
}
void fnMergeSort(int a[],int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
fnMergeSort(a,low,mid);
fnMergeSort(a,mid+1,high);
fnMerge(a,low,mid,high);
}
}
void fnGenRandInput(int x[], int n)

Dept. of MCA, The Oxford College of Engineering Page 43


3 Semester Lab Manual
{
int i;
srand(time(NULL));
for(i=0;i<n;i++)
{
x[i] = rand()%10000;
}
}
void fnDispArray( int x[], int n)
{
int i;
for(i=0;i<n;i++)
printf(" %5d \n",x[i]);
}

OUTPUT

Enter the number of elements to sort Sorted Array


10
382
Unsorted Array 814
814 1035
9035 2768
5524 3683
6297 5524
382 6297
6911 6308
1035 6911
3683 9035
2768 Time taken 0.000004
6308

N- Values Mergesort
10 0.000004
20 0.000006
30 0.000008
40 0.00001
50 0.000012

4. Obtain the Topological ordering of vertices in a given digraph.

Algorithm
Step 1: Identify the source,which is the vertex with no incoming edges.
Step 2: Delete it along with all the edges outgoing from it if thereare several sources, break
the tie arbitarily.

Dept. of MCA, The Oxford College of Engineering Page 44


3 Semester Lab Manual
Step 3: The order in which the vertices are deleted yields a solution to the topological sorting
problem.

Program:
#include<stdio.h>
int main()
{
int i,j,k,n,a[10][10],indegree[10],flag[10],count=0,s[10],t=0,u;
system("clear");
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the adjacency matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
{
indegree[i]=0;
flag[i]=0;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
indegree[i]=indegree[i]+a[j][i];
for(i=1;i<=n;i++)
printf("Indegree of %d is %d\n",i,indegree[i]);
printf("The topological ordering is:");
while(count < n)
{
for(k=1;k<=n;k++)
if((indegree[k]==0)&&(flag[k]==0))//remove vertex which is having indegree 0
s[t++]=k;
u = s[--t];
printf("%d\t",u);
flag[u]=1;
for(i=1;i<=n;i++)
if(a[u][i]==1)
indegree[i]--;
count++;
}
}

OUTPUT 1

Enter the number of vertices:5

A D
A

B E

Enter the adjacency matrix

Dept. of MCA, The Oxford College of Engineering Page 45


3 Semester Lab Manual
00100
00100
00011
00001
00000

Indegree of 1 is 0
Indegree of 2 is 0
Indegree of 3 is 2
Indegree of 4 is 1
Indegree of 5 is 2

The topological ordering is:


2 1 3 4 5

OUTPUT 2

Enter the number of vertices:3


A B
A A

C
A matrix
Enter the adjacency
010
001
100
Indegree of 1 is 1
Indegree of 2 is 1
Indegree of 3 is 1
It is a cyclic Graph and we cannot sort using Topological Sorting Technique.

5. Implement 0/1 Knapsack problem using Dynamic Programming

AlgorithmKnapsack(n,m,w,p,v)
// Purpose : To find the optimal solution for knapsack problem
// Input : n- Number of object to be selected
m- Capacity of the knapsack
w- Weight of all the object
p- Profit of all the object
// Output : v- The optimal solution for the number selecte with specified remaining capacity
for 0 to n do
for 0 to m do
if(i=0 or j=0)
v[i,j]=0
else if(w[i]>j)
v[i,j]=v[i-1,j]
else
v[i,j]=max(v[i-1,j] , v[i-1,j-w[i]]+p[i])
end if
end for

Dept. of MCA, The Oxford College of Engineering Page 46


3 Semester Lab Manual
end for
return

Program:
#include<stdio.h>
int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
void knapsack(int m,int n,int w[],int p[])
{
int v[10][10],x[10],i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
{
if(j==0||i==0)
v[i][j]=0;
else
if(j<w[i])
v[i][j]=v[i-1][j];
else
v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
}
}
printf("\nTHE SOLUTION TABLE \n");
for(i=0;i<=n;i++)
{
for(j=0;j<=m;j++)
printf("%d\t",v[i][j]);
printf("\n");
}
printf("\nTHE OPTIMAL SOLUTION IS:%d",v[n][m]);
for(i=1;i<=n;i++)
x[i]=0;
i=n;
j=m;
while(i!=0&&j!=0)
{
if(v[i][j]!=v[i-1][j])
{
x[i]=1;
j=j-w[i];
}
i--;
}
printf("\nTHE ITEMS SELECTED ARE:");
for(i=1;i<=n;i++)
printf("x[%d]=%d\n",i,x[i]);
}
void main()

Dept. of MCA, The Oxford College of Engineering Page 47


3 Semester Lab Manual
{
int w[10],p[10],i,m,n;
system(" clear");
printf("\n ENTER THE NUMBER OF ITEMS:");
scanf("%d",&n);
printf("\n ENTER THE WEIGHTS OF THE ITEMS:\n");
for(i=1;i<=n;i++)
scanf("%d",&w[i]);
printf("\n ENTER THE PROFITS OF THE ITEMS:\n");
for(i=1;i<=n;i++)
scanf("%d",&p[i]);
printf("\n ENTER THE CAPACITY OF KNAPSACK:");
scanf("%d",&m);
knapsack(m,n,w,p);
}

OUTPUT

ENTER THE NUMBER OF ITEMS:4

ENTER THE WEIGHTS OF THE ITEMS:


2132

ENTER THE PROFITS OF THE ITEMS:


12 10 20 15

ENTER THE CAPACITY OF KNAPSACK:5

THE SOLUTION TABLE


0 0 0 0 0 0
0 0 12 12 12 12
0 10 12 22 22 22
0 10 12 22 30 32
0 10 15 25 30 37

THE OPTIMAL SOLUTION IS:


37
THE ITEMS SELECTED ARE:
x[1]=1
x[2]=1
x[3]=0
x[4]=1

6. From a given vertex in a weighted connected graph, find shortest paths to other vertices using
Dijkstra's algorithm.

Algorithm Single_source_shortest_path(v,cost,dist,n)
//dist[j],1<=j<=n,is the length of the shortest path from vertex v to vertex j in
//digraph G with n verices. dist[v] is set of 0. G is represented by its cost adjacency
//matrix cost[1:n,1:n].
{
for i 1 to n do
{
//initialize S

Dept. of MCA, The Oxford College of Engineering Page 48


3 Semester Lab Manual
S[i]=false
dist[i] cost[v,i]
}
S[v] true
dist[v] 0.0 //put v in S
for num 2 to n do
{
//determine n-1 paths from v
Choose u from V-S such that dist[u] is minimum
S[u] true //put u in S
for(each w adjacent to u with S[w]=false) do
//Update distances
if(dist[w]>dist[u]+cost[u,w])than
dist[w] dist[u]+cost[u,w]
}
}

Program:
#include<stdio.h>
void dijj(int,int,int [][10],int[],int[]);
void main()
{
int dest,n,s,i,j,cost[10][10],dist[10],path[10];
printf("\nEnter no.of vertices");
scanf("%d",&n);
printf("\n Enter cost adjacency matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
printf("\nEnter source vertex");
scanf("%d",&s);
dijj(n,s,cost,dist,path);
printf("\nShortest path \n");
for(i=1;i<=n;i++)
{
dest=i;
if(i!=s)
{
if(dist[i]==9999)
printf("\nvertex %d is not reachable",i);
else
{
printf("\nShortest distance from %d to %d is %d\n",s,i,dist[i]);
while(dest!=s)
{
printf(" %d<-",dest);
dest=path[dest];
}
printf("%d\n",dest);
}
}
}
}

Dept. of MCA, The Oxford College of Engineering Page 49


3 Semester Lab Manual
void dijj(int n,int s,int c[10][10],int dist[10],int path[10])
{
int i,v,u,w,visited[10],min,count;
for(i=1;i<=n;i++)
visited[i]=0,path[i]=s,dist[i]=c[s][i];
count=2;
while(count<=n)
{
min=999;
for(u=1;u<=n;u++)
if(dist[u]<min && dist[u]!=0 && visited[u]==0)
min=dist[u],w=u;
visited[w]=1;
count++;
for(v=1;v<=n;v++)
if(dist[w]+c[w][v]<dist[v]&&visited[v]!=1)
{
dist[v]=dist[w]+c[w][v];
path[v]=w;
}
}
}

OUTPUT
Enter no.of vertices
6

Enter cost adjacency matrix


0 80 40 999 60 999
80 0 999 100 999 999
40 999 0 20 120 60
999 100 20 0 999 120
60 999 120 999 0 40
999 999 60 120 40 0

Enter source vertex


1

Shortest path
Shortest distance from 1 to 2 is 80
2<-1

Shortest distance from 1 to 3 is 40


3<-1

Shortest distance from 1 to 4 is 60


4<- 3<-1

Shortest distance from 1 to 5 is 60


5<-1

Shortest distance from 1 to 6 is 100


6<- 3<-1

Dept. of MCA, The Oxford College of Engineering Page 50


3 Semester Lab Manual
7. Sort a given set of elements using the Quicksort method and determine the time required to sort
the elements. Repeat the experiment for different values of n, the number of elements in the list to
be sorted and plot a graph of the time taken versus n. The elements can be read from a file or can
be generated using the random number generator.

Algorithm quicksort(p,q)
//Sorts the elements a[p],…..a[q] which reside in the global
//array a[1:n] into ascending order;a[n+1] is considered to
//be defined and must be >= all the elements in a[1:n].
{
if(p<q) then
{
//divide P into two subproblems.
j:=Partition(a,p,q+1);
//j is the position of the portioning element.
quicksort(p,j-1);
quicksort(j+1,q);
}
}

Program:

#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>

void fnGenRandInput(int *,int);


void fnDispArray(int *,int);
int partition(int *,int,int);
void quicksort(int *,int,int);
void swap(int *,int ,int );

int main()
{
system("clear");
struct timeval tv;
double dStart,dEnd;
int a[100],iNum;
printf("\nEnter the number of elements to sort\n");
scanf("%d",&iNum);
printf("\nUnsorted Array\n");
fnGenRandInput(a,iNum);
fnDispArray(a,iNum);
gettimeofday(&tv,NULL);
dStart = tv.tv_sec + (tv.tv_usec/1000000.0);
quicksort(a,0,iNum-1);
gettimeofday(&tv,NULL);
dEnd = tv.tv_sec + (tv.tv_usec/1000000.0);
printf("\n\nTime taken by quicksort %.6lf\n",dEnd-dStart);
printf("\nSorted Array\n");
fnDispArray(a,iNum);
return 0;
}

Dept. of MCA, The Oxford College of Engineering Page 51


3 Semester Lab Manual
void swap(int *a,int x, int y)
{
int t=a[x]; a[x]=a[y]; a[y]=t;
}

int partition(int *a,int low, int high)


{
int i, j, p;
p=a[low];
i=low;
j=high+1;
while(i<=j)
{
do { i++; } while(a[i]<=p);
do { j--; } while(a[j]>p);
if(i<j)
swap(a,i, j);
}
a[low]=a[j];
a[j]=p;
return j;
}

void quicksort(int *a,int low, int high)


{
int p;
if(low<high)
{
p=partition(a,low, high);
quicksort(a,low, p-1);
quicksort(a,p+1, high);
}
}

void fnGenRandInput(int *a,int n)


{
int i;
srand(time(NULL));
for(i=0;i<n;i++)
{
a[i] = rand()%1000;
}
}
void fnDispArray(int *a,int n)
{
int i;
for(i=0;i<n;i++)
printf(" %5d \t",a[i]);
}

Dept. of MCA, The Oxford College of Engineering Page 52


3 Semester Lab Manual
OUTPUT

Enter the number of elements to sort


10

Unsorted Array
101 464 157 918 555 878 504 39 211 321

Time taken by quicksort 0.000003

Sorted Array
39 101 157 211 321 464 504 555 878 918

N Time
10 0.000003
20 0.000005
30 0.000006
40 0.000007
50 0.000009

8. Find Minimum Cost Spanning Tree of a given undirected graph using Kruskal's algorithm.

Algorithm Kruskal(E,cost,n,t)
{
// E is the set of Edges in G. G has n vertices.
// cost[u,v] is the cost of edge[u,v]
// T is the set of edges in Minimum Cost Spanning Tree. The total cost is returned as
Output.
Construct a heap out of the edge costs using heapify.
for i 1 to n do parent[i] -1
// each vertex is in a different set.

Dept. of MCA, The Oxford College of Engineering Page 53


3 Semester Lab Manual
i 0
mincost 0.0
while((i<n-1)and(heap not empty))do
{
Delete a minimum cost edge(u,v) from the heap and reheapify using Adjust
j find(u)
k find(v)
if(j≠k) then
{
i i+1
t[i,1] u
t[i,2] v
mincost mincost+cost[u,v]
union(j,k)
}
}
if(i≠n-1) then write(“no spanning tree”)
else return mincost
}

Program:
#include<stdio.h>
#include<stdlib.h>
int parent[10],min,n,i,count=1,cost[10][10],sum=0;
void main()
{
int a,u,b,v,j;
system("clear");
printf("Enter the no of vertices:");
scanf("%d",&n);
printf("Enter the cost matrix\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&cost[i][j]);
for(i=1;i<=n;i++) parent[i]=i;
while(count < n)
{
for(i=1,min=99;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j] < min && cost[i][j] != 0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(min == 99)
{
system("clear");
printf("\n No spanning tree \n");
exit(1);
}
while(parent[u]!=u)
u=parent[u];
while(parent[v]!=v)

Dept. of MCA, The Oxford College of Engineering Page 54


3 Semester Lab Manual
v=parent[v];
if(u!=v)
{
count++;
printf("\nEdge <%d %d> = %d",a,b,min);
sum+=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Cost of MST %d",sum);

Output:
Enter the no of vertices:6
Enter the cost matrix

0 60 10 999 999 999


60 0 999 20 40 70
10 999 0 999 999 50
999 20 999 0 999 80
999 40 999 999 0 30
999 70 50 80 30 0

Edge <1 3> = 10


Edge <2 4> = 20
Edge <5 6> = 30
Edge <2 5> = 40
Edge <3 6> = 50

Cost of MST 150

09. Check whether a given graph is connected or not using DFS method.

Algorithm:
DFS(G)
//Implemnts a depth-first search traversal of a given graph
//Input:Graph G={V.E}
//Output:Graph G with its vertices marked with consecutive integers in the order they’ve been first
encountered by the DFS traversal mark each Vertex in V with 0 as a mark of being “unvisited”

Count<-0
For each vertex v in V do
If v is marked with 0
Dfs(v)
//visits recursively all the unvisited vertices connected to vertex v and
//assigns them the numbers in the order they are encountered
//via global variable count
Count<-count+1;mark v with count
For each vertex w in V adjacent to v do
Dept. of MCA, The Oxford College of Engineering Page 55
3 Semester Lab Manual
If w is marked with 0
Dfs(w)

Program:
#include<stdio.h>
int adj[20][20], n ,s,visit[20], count=1;
void dfs(int);
int main()
{
int i,j;
system("clear");
printf("Enter the number of vertices:");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&adj[i][j]);
for(i=1;i<=n;i++)
visit[i]=0;

dfs(1);

if (count==n)
printf("\nThe graph is connected");
else
printf("\nThe Graph is not connected.");
}

void dfs(int v)
{
int w;
visit[v]=1;
for(w=1;w<=n;w++)
if ((adj[v][w]==1) && (visit[w]==0))
{
dfs(w);
count++;
}
}

OUTPUT

Enter the number of vertices:4


Enter the adjacency matrix:
0100
0010
0001
1000

The graph is connected

Enter the number of vertices:4

Dept. of MCA, The Oxford College of Engineering Page 56


3 Semester Lab Manual
Enter the adjacency matrix:
0100
0001
0000
1000

The graph is not connected

10. Find a subset of a given set S = {sl,s2,.....,sn} of n positive integers whose sum is equal to a given
positive integer d. For example, if S= {1, 2, 5, 6, 8} and d = 9 there are two solutions {1,2,6}
and{1,8}.A suitable message is to be displayed if the given problem instance doesn't have a solution.

Algorithm
Algorithm sumOfSubset(s, k, r)
{
//s – partial sum, k – k element in consideration, r – remaining sum
X[k]=1;
if (S+W[k]=m) then
write(X[1:k]); // there is no recursive call here as W[j]>0,1<=j<=n.
else if (S+W[k]+W[k+1]<=m) then
sumofsubset (S+W[k], k+1,r- W[k]);

if ((S+ r- W[k]>=m)and(S+ W[k+1]<=m)) then


{
X{k]=0;
sumofsubset (S, k+1, r- W[k]);
}
}
Program:

#include<stdio.h>
#include<math.h>
int s[30], x[30], d, n; //Global variables
int flag=0;
//Function to find optimal subset
void subset(int m, int k, int r)
{
int i,c=0;
x[k]=1; //Mark kth element as included
if (m+s[k]==d) //If inclusion gives sum as d,
{
printf("\nSubset %d:{",++c );
for(i=1;i<=n;i++) //print the elements of the subset
if (x[i]==1)
{
printf("%d ",s[i]);
flag=1; //Set flag to indicate existence of subset
}
printf("}\n");
}
else
{
if (m+s[k]+s[k+1]<=d) //Else check for next element
{

Dept. of MCA, The Oxford College of Engineering Page 57


3 Semester Lab Manual
subset(m+s[k],k+1,r-s[k]); //Include next element in subset
x[k+1]=0;
}
if ((m+r-s[k]>=d) && (m+s[k+1]<=d))
{
x[k]=0;
subset(m,k+1,r-s[k]);
x[k+1]=0;
}
}
}
void main()
{
int sum=0,i;
system("clear");
printf("\nEnter the number of elements in the set:");
scanf("%d",&n);
printf("\nEnter Set in increasing order:");
for(i=1;i<=n;i++)
scanf("%d", &s[i]);
printf("\nEnter Maximum subset value: ");
scanf("%d",&d); //Input maximum sum limit
for(i=1;i<=n;i++)
sum= sum+s[i]; //Calculate sum of all set elements
if (sum<d||s[1]>d) //Check for necessary conditions
printf("\nNo subset possible");
else
{
subset(0,1,sum); //Call function to find optimal subset
if (flag==0) //Display message if no suitable subset is found
printf("\nNo subset possible");
}
}

OUTPUT

Enter the number of elements in the set:


6

Enter Set in increasing order:2 4 6 8 10 12

Enter Maximum subset value: 5

No subset possible

OUTPUT

Enter the number of elements in the set:5

Enter Set in increasing order:


12568
Enter Maximum subset value: 9
Subset 1:{1 2 6 }
Subset 1:{1 8 }

Dept. of MCA, The Oxford College of Engineering Page 58


3 Semester Lab Manual

11a. Implement Horspool algorithm for String Matching.

Algorithm Shift_table(p,s)
// Purpose : to fill the shift table , based on the pattern string
// Input : p- pattern string to be searched
// Output : t- shift table is returned through parameter
m length(p)
for i 0 to 127 do
s[i] m
end for
for i 0 to m-2 do
s[p[i]] m-1-i
end for
return

Algorithm Horspool(p,t)
// Purpose : to check whether the pattern is present in text string
// Input : p- pattern string , t- text string
// Output : position of match if successful -1 otherwise
Shift_table(p,s)
n length(t)
m length(p)
i m-1
while(i<=n-1) do
k 0
while(k<=m-1 and t[i-k]=p[m-1-k]) do
k k+1
end while
if(k=m) return i-m+1
i i+s[t[i]]
end while
return -1

Program:
#include<stdio.h>
#include<string.h>
#define MAX 500
int t[MAX];

void shifttable(char p[])


{
int i,j,m;
m=strlen(p);
for(i=0;i<MAX;i++)
t[i]=m;
for(j=0;j<m-1;j++)
t[p[j]]=m-1-j;
}
int horspool(char src[],char p[])
{
int i,j,k,m,n;
n=strlen(src);
m=strlen(p);

Dept. of MCA, The Oxford College of Engineering Page 59


3 Semester Lab Manual
printf("\nLength of text=%d",n);
printf("\n Length of pattern=%d",m);
i=m-1;
while(i<n)
{
k=0;
while((k<m)&&(p[m-1-k]==src[i-k]))
k++;
if(k==m)
return(i-m+1);
else
i+=t[src[i]];
}
return -1;
}
void main()
{
char src[100],p[100];
int pos;
system("clear");
printf("Enter the text in which pattern is to be searched:\n");
gets(src);
printf("Enter the pattern to be searched:\n");
gets(p);
shifttable(p);
pos=horspool(src,p);
if(pos>=0)
printf("\n The desired pattern was found starting from position %d",pos+1);
else
printf("\n The pattern was not found in the given text\n");

OUTPUT
Enter the text in which pattern is to be searched:
THE OXFORD COLLEGE OF ENGINEERING
Enter the pattern to be searched:
OF

Length of text=33
Length of pattern=2
The desired pattern was found starting from position 20

OUTPUT
Enter the text in which pattern is to be searched:
we are located at bommanahalli

Enter the pattern to be searched:


oxford

Length of text=31
Length of pattern=6
The pattern was not found in the given text

Dept. of MCA, The Oxford College of Engineering Page 60


3 Semester Lab Manual
11b. Find the Binomial Co-efficient using Dynamic Programming.

Algorithm binomial_coefficient(n,k)
// Purpose : to compute binomial by dynamic programming
// Input : non negative integers such that n≥k≥0
// Output : value of C(n, k)
for i 0 to n do
for j 0 to min(i, k) do
if(j=0 or i=j)
c[i, j] 1
else
c[i, j] c[i-1,j-1]+c[i-1,j]
end if
end for
end for
return c[n,k]

Program:
#include<stdio.h>
long int bin(int n,int k)
{
int i,j;
long int arr[20][20];
for(i=0;i<=n;i++)
{
for(j=0;j<=(k<i?k:i);j++)
{
if(i==j||j==0)
{
arr[i][j]=1;
}
else
{
arr[i][j]=arr[i-1][j]+arr[i-1][j-1];
}
}
}
printf("\nThe Binomial matrix is :\n\t");
for (i=0; i<=k; i++)
printf("%d\t",i);
printf("\n");
for (i=0; i<=n+1; i++)
printf("========");
printf("\n");
for (i=0; i<=n; i++)
{
printf("i=%d\t",i);
for(j=0;j<=(k<i?k:i);j++)
{
printf("%ld\t",arr[i][j]);
}
printf("\n");
}
printf("\n");

Dept. of MCA, The Oxford College of Engineering Page 61


3 Semester Lab Manual

return(arr[n][k]);
}

void main()
{
int n,k;
system("clear");
printf("\nEnter the value of n ");
scanf("%d",&n);
printf("\nEnter the value of k ");
scanf("%d",&k);
if(n<0||k<0||k>n)
{
printf("\nValue cannot be calculated!!");
}
else
{
printf("\nThe binomial coefficient is %ld.",bin(n,k));
}
}

OUTPUT
Enter the value of n
5

Enter the value of k


2

The Binomial matrix is :


0 1 2
========================================================
i=0 1
i=1 1 1
i=2 1 2 1
i=3 1 3 3
i=4 1 4 6
i=5 1 5 10

OUTPUT
Enter the value of n
4

Enter the value of k


4

The Binomial matrix is :


0 1 2 3 4
================================================
i=0 1
i=1 1 1
i=2 1 2 1
i=3 1 3 3 1
i=4 1 4 6 4 1

Dept. of MCA, The Oxford College of Engineering Page 62


3 Semester Lab Manual
12. Find Minimum Cost Spanning Tree of a given undirected graph using Prim’s algorithm.

Algorithm Prims(c,n)
//Assume that G is connected undirected and weighted graph
//Input: the cost adjacency matrix C and number of vertices n
//Output: minimum cost spanning tree T
For i=1 to n
visited[i]=0 //initialize all vertices as unvisited
[end for]
u=1 // consider vertex 1 as starting vertex
visited[u]=1
while (there is still unchosen vertex) do
{
Let (u,v) be the lightest edge b/w any chosen u to any unchosen vertex v
visited[v]=1
T=union(T,<u,v>) // add edge (u,v) to spanning tree
}
return T

Program:
#include<stdio.h>
#include<stdlib.h>
void main()
{
int i,j,k,v,u,min,n,tot=0;
int vt[100],c[100][100];
system("clear");
printf("Enter the no of vertices:");
scanf("%d",&n);
printf("Enter the cost matrix");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&c[i][j]);
for(i=1;i<=n;i++)
vt[i]=0;
vt[1]=1;
for(i=1;i<=n-1;i++)
{
min=99;
for(j=1;j<=n;j++)
{
if(vt[j]==1)
{
for(k=1;k<=n;k++)
if(c[j][k] != 0 && (c[j][k] <= min) &&vt[k]!= 1)
{
min=c[j][k];
v=j;
u=k;
}
}
}
vt[u]=1;
tot+=min;

Dept. of MCA, The Oxford College of Engineering Page 63


3 Semester Lab Manual
if(min == 99)
{
system("clear");
printf("\nNo spanning tree exists\n");
exit(0);
}
else
printf("\n Edge< %d , %d>= %d",v,u,min);
}
printf("\n Minimum cost = %d",tot);
}

OUTPUT
Enter the no of vertices:
5
Enter the cost matrix
0 2 999 5 999
2 999 14 5 4
999 14 0 999 34
5 5 999 0 58
999 4 34 58 0

Edge< 1 , 2>= 2
Edge< 2 , 5>= 4
Edge< 2 , 4>= 5
Edge< 2 , 3>= 14
Minimum cost = 25

OUTPUT
Enter the no of vertices:5
Enter the cost matrix
0 999 10 7 999
999 0 999 32 999
10 999 0 9 999
7 32 9 0 23
999 999 999 23 0

Edge< 1 , 4>= 7
Edge< 4 , 3>= 9
Edge< 4 , 5>= 23
Edge< 4 , 2>= 32
Minimum cost = 71

13a. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths Problem.

Algorithm floyd(n,cost,D)
// Purpose : to implement floyd’s algorithm (all- pairs shortest paths problem)
// Input : cost adjacency matrix cost of size n*n
// Output : shortest distance matrix of size n*n
fori 0 to n-1 do
for j 0 to n-1 do
D[i,j] cost[i,j]
end for

Dept. of MCA, The Oxford College of Engineering Page 64


3 Semester Lab Manual
end for
for k 0 to n-1 do
fori 0 to n-1 do
for j 0 to n-1 do
D[i,j] min(D[I,j] , D[i,k]+D[k,j])
end for
end for
end for
return

Program:
#include<stdio.h>
#include<stdlib.h>
int n,a[15][15];
int imin(int a,int b)
{
return(a<b?a:b);
}
void main()
{
int i,j,k;
printf("\nEnter the no of vertices");
scanf("%d",&n);
printf("\nEnter the adjacency matrix");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for ( k = 0; k < n; k++ )
{
for ( i = 0; i< n; i++ )
{
for ( j = 0; j < n; j++ )
{
a[i][j] = imin( a[i][j], a[i][k] + a[k][j] );
}
}
}
printf("\nThe all pair shortest path matrix is");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
}

OUTPUT
Enter the no of vertices

Dept. of MCA, The Oxford College of Engineering Page 65


3 Semester Lab Manual
4

Enter the adjacency matrix


1 999 3 999
2 0 999 999
999 7 0 1
6 999 999 0

The all pair shortest path matrix is


1 10 3 4
2 0 5 6
7 7 0 1
6 16 9 0

OUTPUT
Enter the no of vertices
5

Enter the adjacency matrix


0 5 7 999 2
5 0 999 6 3
7 999 0 4 4
999 6 4 0 5
23450

The all pair shortest path matrix is


0 5 6 7 2
5 0 7 6 3
6 7 0 4 4
7 6 4 0 5
2 3 4 5 0

13b. Compute the transitive closure of a given directed graph using Warshall's algorithm.
Algorithm warshall(n,a,p)
// Purpose : to implement warshall’s algorithm (Transitive closure)
// Input : adjacency matrix a of size n*n
// Output : Transitive closure (path matrix) of size n*n
fori 0 to n-1 do
for j 0 to n-1 do
p[i,j] cost[i,j]
end for
end for
for k 0 to n-1 do
fori 0 to n-1 do
for j 0 to n-1 do
if(p[i,j] =0 and(if(p[i,k]=1 and p[k,j]=1))) then
p[i,j] 1
end if
end for
end for
end for
return
Program:

Dept. of MCA, The Oxford College of Engineering Page 66


3 Semester Lab Manual
#include<stdio.h>
int main()
{
int i,j,n,a[50][50],k;
system("clear");
printf("\n Enter the no of edges:");
scanf("%d",&n);
printf("\nEnter the adjecency matrix:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(k=0;k<n;k++)
{
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(a[i][j]==0 && a[i][k]==1&&a[k][j]==1)
a[i][j]=1;
}
printf("\nThe Resultant path matrix is:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d\t",a[i][j]);
printf("\n");
}
return 0;
}

OUTPUT
Enter the no of edges:4

Enter the adjecency matrix:


0100
0010
1001
0000

The Resultant path matrix is:


1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 0

OUTPUT
Enter the no of edges:4

Enter the adjecency matrix:


0100
0010
0001
0000

The Resultant path matrix is:


0 1 1 1

Dept. of MCA, The Oxford College of Engineering Page 67


3 Semester Lab Manual
0 0 1 1
0 0 0 1
0 0 0 0

14. Implement N Queen's problem using Back Tracking.

Algorithm place(x,k)
for i 1 to k-1
if(x[i]=x[k] or (i-k)=(x[i]-x[k]))
return FALSE
end if
end for
return TRUE
// algorithm to place all queen
k 1
x[k] 0
while(k≠0)
x[k] x[k]+1
while((x[k]<=n) && (!place(x,k))
x[k] x[k]+1
end while
if(x[k]<=n)
if(k=n)
print(x1,x2,x3,…..,xn)
else
k++
x[k] 0
end if
else
k—
end if
end while

Program:

#include<stdio.h>
#include<stdlib.h>
int x[10];
int place(int p)
{
int i;
for(i=1;i<=(p-1);i++)
if(x[i]==x[p]||(abs(x[i]-x[p])==(abs(i-p))))
return 0;
return 1;
}
void main()
{
int k,i,j,n,count=1;
system("clear");
printf("\n Enter the number of queens:");
scanf("%d",&n);
if(n==0||n==2||n==3)

Dept. of MCA, The Oxford College of Engineering Page 68


3 Semester Lab Manual
{
printf("\n No solution");
}
else
{
k=1;x[1]=0;
while(k)
{
x[k]=x[k]+1;
while(x[k]<=n && !place(k))
x[k]=x[k]+1;
if(x[k]<=n)
{
if(k==n)
{
printf("\n solution %d:\n",count++);
for(i=1;i<=n;i++)
{
for(j=1;j<x[i];j++)
printf("*\t");
printf("Q\t");
for(j=x[i]+1;j<=n;j++)
printf("*\t");
printf("\n\n");
}
}
else
{
k+=1;x[k]=0;
}
}
else
k-=1;
}
}
}

OUTPUT
Enter the number of queens:3

No solution

OUTPUT
Enter the number of queens:4

solution 1: solution 2:
* Q * * * * Q *

* * * Q Q * * *

Q * * * * * * Q

* * Q * * Q * *

Dept. of MCA, The Oxford College of Engineering Page 69


3 Semester Lab Manual
OUTPUT
Enter the number of queens:6
Solution 1:
* Q * * * *

* * * Q * *

* * * * * Q

Q * * * * *

* * Q * * *

* * * * Q *

Ssolution 2:
* * Q * * *

* * * * * Q

* Q * * * *

* * * * Q *

Q * * * * *

* * * Q * *

Solution 3:
* * * Q * *

Q * * * * *

* * * * Q *

* Q * * * *

* * * * * Q

* * Q * * *

Solution 4:
* * * * Q *

* * Q * * *

Q * * * * *

* * * * * Q

* * * Q * *

* Q * * * *

Dept. of MCA, The Oxford College of Engineering Page 70

You might also like