Professional Documents
Culture Documents
Relational schema:
MUSICIAN
Ssn Name Addrs Phone
PLAYS
Id Ssn
INSTRUMENT
Id Iname M_key
PERFORMS
Ssn Title
SONG
Title Author Aid
ALBUM
Aid Title C_date Format Producer_ssn
create table songs(title varchar (10) primary key, author varchar(20), aid number(4) references
album(aid));
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
desc plays
Name Null? Type
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)
ID INAME MKEY
---------- ------------------------------ ----------
1 guitar high
2 flute flat
3 violin low
4 drums rock
5 piano high
6 tabala low
SSN ID
---------- ----------
123 1
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;
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)
ATITLE
-------
abc
xyz
www
sss
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
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)
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)
PROFID PNO
---------- ----------
1 111
2 222
3 333
4 444
5 555
2 111
2 333
2 444
2 555
USN PNO
---------- ----------
123 111
124 222
125 333
126 444
127 555
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.
Queries3: List the professors and sum of the budget of their projects started after 2005 but ended in 2010.
(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;
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
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:
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
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.
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.
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
TABLE CREATION
TRNAME FORMULA
--------------- ----------
saridon abc
anacin xyz
crocin www
dolopar ggg
cpm qqq
TNAME NAME
---------------- --------------------
saridon cipla
anacin cipla
crocin himalaya
dolopar ranbaxy
PHNAME TNAME
---------------- --------------------
medplus dolopar
apollo crocin
apollo saridon
sai crocin
ganesh cpm
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'))
2) select * from doctor where dssn in (select dssn from prescription where pdate like '%13' group by dssn
having count(pssn)>=2);
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);
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.
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)
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)
PC_NAME PC_ADDRESS
--------------- ---------------
avm chennai
yashraj bangalore
sun bangalore
rockline bangalore
ram mumbai
query1:
query3:
PC_NAME PC_ADDRESS
--------------- --------------
avm Chennai
query4:
query5:
D_NAME
----------
abc
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
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()
expr = "(5+6)*4"
print expr
print Infix(expr), eval(expr)
# 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)
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
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']
def checkPangram(s):
List = []
# create list of 26 characters and set false each entry
for i in range(26):
List.append(False)
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 : ")
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()
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)
currentTime = Time()
currentTime.hours = 9
currentTime.minutes = 14
currentTime.seconds = 30
breadTime = Time()
breadTime.hours = 3
breadTime.minutes = 35
breadTime.seconds = 40
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
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");
OUTPUT
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;
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
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);
OUTPUT
N- Values Mergesort
10 0.000004
20 0.000006
30 0.000008
40 0.00001
50 0.000012
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.
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
A D
A
B E
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
OUTPUT 2
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.
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
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()
OUTPUT
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
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);
}
}
}
}
OUTPUT
Enter no.of vertices
6
Shortest path
Shortest distance from 1 to 2 is 80
2<-1
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>
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;
}
Unsorted Array
101 464 157 918 555 878 504 39 211 321
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.
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)
Output:
Enter the no of vertices:6
Enter the cost matrix
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
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]);
#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
{
OUTPUT
No subset possible
OUTPUT
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];
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
Length of text=31
Length of pattern=6
The pattern was not found in the given text
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");
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
OUTPUT
Enter the value of n
4
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;
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
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
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
OUTPUT
Enter the no of vertices
5
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:
OUTPUT
Enter the no of edges:4
OUTPUT
Enter the no of edges:4
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)
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 * *
* * * 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 * * * *