You are on page 1of 51

PART-A

1. Aim: Write a program to implement the deque (double ended queue) ADT using a doubly
linked list.
Source Code:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
class node
{
public:
int data;
class node *next;
class node *prev;
};
class dqueue: public node
{
node *head,*tail;
int top1,top2;
public:
dqueue()
{
top1=0;
top2=0;
head=NULL;
tail=NULL;
}
void push(int x){
node *temp;
int ch;
if(top1+top2 >=5)
{
cout <<"dqueue overflow";
return ;
}
if( top1+top2 == 0)
{
head = new node;
head->data=x;
head->next=NULL;
head->prev=NULL;
tail=head;
top1++;
}
else
{
cout <<" Add element 1.FIRST 2.LAST\n enter ur choice:";
cin >> ch;
if(ch==1)
{
top1++;
temp=new node;
temp->data=x;
temp->next=head;
temp->prev=NULL;
head->prev=temp;
head=temp;
}
else
{
top2++;
temp=new node;
temp->data=x;
temp->next=NULL;
temp->prev=tail;
tail->next=temp;
tail=temp;
}

}
}
void pop()
{
int ch;
cout <<"Delete 1.First Node 2.Last Node\n Enter ur choice:";
cin >>ch;
if(top1 + top2 <=0)
{
cout <<"\nDqueue under flow";
return;
}
if(ch==1)
{
head=head->next;
head->prev=NULL;
top1--;
}
else
{
top2--;
tail=tail->prev;
tail->next=NULL;
}
}

void display()
{
int ch;
node *temp;
cout <<"display from 1.Staring 2.Ending\n Enter ur choice";
cin >>ch;
if(top1+top2 <=0)
{
cout <<"under flow";
return ;
}
if (ch==1)
{
temp=head;
while(temp!=NULL)
{
cout << temp- >data <<" ";
temp=temp->next;
}
}
else
{
temp=tail;
while( temp!=NULL)
{
cout <<temp->data << " ";
temp=temp->prev;
}
}
}
};
main()
{
dqueue d1;
int ch;
while (1){
cout <<"1.INSERT 2.DELETE 3.DISPLAU 4.EXIT\n Enter ur choice:";
cin >>ch;
switch(ch)
{
case 1: cout <<"enter element";
cin >> ch;
d1.push(ch); break;
case 2: d1.pop(); break;
case 3: d1.display(); break;
case 4: exit(1);
}
}}
OUTPUT
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:1
enter element4
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:1
enter element5
Add element 1.FIRST 2.LAST
enter ur choice:1
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:1
enter element6
Add element 1.FIRST 2.LAST
enter ur choice:2
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:3
display from 1.Staring 2.Ending
Enter ur choice1
546
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:2
Delete 1.First Node 2.Last Node
Enter ur choice:1
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:3
display from 1.Staring 2.Ending
Enter ur choice1
1.INSERT 2.DELETE 3.DISPLAU 4.EXIT
Enter ur choice:4

2. a) Aim: Program to implement Breadth First Search


Source Code:
#include<iostream.h>
#include<conio.h>
struct node
{
int data,status;
struct node *next;
struct link *adj;
};
struct link
{
struct node *next;
struct link *adj;
};
struct node *start,*p,*q;
struct link *l,*k;
template<class T>
class BFS
{
public:
void cgraph();
void breadth();
};
template<class T>
void BFS<T>::cgraph()
{
T num,flag=0,count=1;
start=NULL;
while(1)
{
cout<<"enter "<<count<<" node (0 to end):";
cin>>num;
count++;
if(num==0)
break;
p=new node;
p->data=num;
p->status=0;
p->next=NULL;
p->adj=NULL;
if(flag==0)
{
start=p;
q=p;
flag++;
}
else
{
q->next=p;
q=p;
}
}
p=start;
while(p!=NULL)
{
cout<<"enter the links to"<<p->data<<"(0 to end): ";
flag=0;
while(1)
{
cin>>num;
if(num==0)
break;
k=new link;
k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{
l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==num)
k->next=q;
q=q->next;
}
}
p=p->next;
}
return;
}
template<class T>
void BFS<T>::breadth()
{
T qu[20],i=1,j=0;
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
qu[0]=p->data;
p->status=1;
while(1)
{
if(qu[j]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==qu[j])
break;
p=p->next;
}
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
qu[i]=q->data;
q->status=1;
qu[i+1]=0;
i++;
}
k=k->adj;
}
j++;
}
j=0;
cout<<"\n Breadth first traversal \n";
while(qu[j]!=0)
{
cout<<qu[j]<<" ";
j++;
}
return;
}
void main()
{
clrscr();
BFS<int>b;
b.cgraph();
b.breadth();
getch();
}

OUTPUT:
enter 1 node (0 to end):1
enter 2 node (0 to end):2
enter 3 node (0 to end):3
enter 4 node (0 to end):4
enter 5 node (0 to end):5
enter 6 node (0 to end):0
enter the links to1(0 to end):
2
3
0
enter the links to2(0 to end):
1
4
0
enter the links to3(0 to end):
1
4
0
enter the links to4(0 to end):
2
3
5
0
enter the links to5(0 to end):
4
0
Breadth first traversal
1 2 3 4 5
b) Aim: Program to Implement Depth First Search
Source Code:
#include<iostream.h>
#include<conio.h>
struct node
{
int data,status;
struct node *next;
struct link *adj;
};
struct link
{
struct node *next;
struct link *adj;
};
struct node *start,*p,*q;
struct link *l,*k;
template<class T>
class DFS
{
public:
void cgraph();
void Depth();
};
template<class T>
void DFS<T>::cgraph()
{
T num,flag=0,count=1;
start=NULL;
while(1)
{
cout<<"Enter "<<count<<" Node(0 to end):";
cin>>num;
count++;
if(num==0)
break;
p=new node;
p->data=num;
p->status=0;
p->next=NULL;
p->adj=NULL;
if(flag==0)
{
start=p;
q=p;
flag++;
}
else
{
q->next=p;
q=p;
}
}
p=start;
while(p!=NULL)
{
cout<<"Enter the links to "<<p->data<<" (0 to end):";
flag=0;
while(1)
{
cin>>num;
if(num==0)
break;
k=new link;
k->adj=NULL;
if(flag==0)
{
p->adj=k;
l=k;
flag++;
}
else
{
l->adj=k;
l=k;
}
q=start;
while(q!=NULL)
{
if(q->data==num)
k->next=q;
q=q->next;
}
}
p=p->next;
}
return;
}
template<class T>
void DFS<T>::Depth()
{
T stack[20],top=1;
cout<<"DEPTH FIRST TRAVERSAL\n\n";
p=start;
while(p!=NULL)
{
p->status=0;
p=p->next;
}
p=start;
stack[0]=0;
stack[top]=p->data;
p->status=1;
while(1)
{
if(stack[top]==0)
break;
p=start;
while(p!=NULL)
{
if(p->data==stack[top])
break;
p=p->next;
}
cout<<stack[top]<<" ";
top--;
k=p->adj;
while(k!=NULL)
{
q=k->next;
if(q->status==0)
{
top++;
stack[top]=q->data;
q->status=1;
}
k=k->adj;
} }
return;
}
void main()
{
clrscr();
DFS<int>D;
D.cgraph();
D.Depth();
getch();
}
OUTPUT:
Enter 1 Node(0 to end):4
Enter 2 Node(0 to end):3
Enter 3 Node(0 to end):2
Enter 4 Node(0 to end):1
Enter 5 Node(0 to end):0
Enter the links to 4 (0 to end):
1
2
0
Enter the links to 3 (0 to end):
1
2
0
Enter the links to 2 (0 to end):
3
4
0
Enter the links to 1 (0 to end):
3
4
0
DEPTH FIRST TRAVERSAL
4 2 3 1
3.Aim: Write a Program to Implement Binary Search Tree Operations
Source Code:
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct node
{
public:
int data;
node *left;
node *right;
};
typedef struct node *NODE;
template<class T>
class BST
{
public:
void insert_BST(T x,NODE &);
void delete_BST(T x,NODE &);
T delete_MIN(NODE &);
NODE Find_MIN(NODE &);
NODE Find_MAX(NODE &);
void Find(T x,NODE &);
void inorder(NODE &);
void preorder(NODE &);
void postorder(NODE &);
void makeEmpty(NODE &);
};
template<class T>
void BST<T>::makeEmpty(NODE &t)
{
NODE temp;
if(t!=NULL)
{
makeEmpty(t->left);
makeEmpty(t->right);
temp=t;
t=NULL;
delete(temp);
}
}
template<class T>
void BST<T>::insert_BST(T x,NODE &p)
{
if(p==NULL)
{
p=new node;
p->data=x;
p->left=NULL;
p->right=NULL;
}
else
{
if(x<p->data)
insert_BST(x,p->left);
else if(x>p->data)
insert_BST(x,p->right);
else
cout<<"\nElement already exists\n";
}
}
template<class T>
void BST<T>::delete_BST(T x,NODE &p)
{
NODE temp;
if(p==NULL)
cout<<"Element not found!!!\n";
else if(x<p->data)
delete_BST(x,p->left);
else if(x>p->data)
delete_BST(x,p->right);
else if((p->left==NULL)&&(p->right==NULL))
{
temp=p;
delete(temp);
p=NULL;
}
else if(p->left==NULL)
{
temp=p;
p=p->right;
delete(temp);
}

else if(p->right==NULL)
{
temp=p;
p=p->left;
delete(temp);
}
else
p->data=delete_MIN(p->right);
}

template<class T>
T BST<T>::delete_MIN(NODE &p)
{
int c;
if(p->left==NULL)
{
c=p->data;
p=p->right;
return c;
}
else
c=delete_MIN(p->left);
return c;
}
template<class T>
void BST<T>::Find(T x,NODE &t)
{
if(t==NULL)
cout<<"\nElement not found\n";
else
{
if(x<t->data)
Find(x,t->left);
else if(x>t->data)
Find(x,t->right);
else
cout<<"\nELEMENT FOUND!!!\n";
}
}
template<class T>
NODE BST<T>::Find_MIN(NODE &p)
{

if(p==NULL)
{
cout<<"\nTree is empty\n";
return p;
}
else
{
while(p->left!=NULL)
p=p->left;
return p;
}
}
template<class T>
NODE BST<T>::Find_MAX(NODE &p)
{
if(p==NULL)
{
cout<<"\nTree is empty\n";
return p;
}
else
{
while(p->right!=NULL)
p=p->right;
return p;
}
}
template<class T>
void BST<T>::inorder(NODE &t)
{
if(t!=NULL)
{
inorder(t->left);
cout<<t->data<<" ";
inorder(t->right);
}
}
template<class T>
void BST<T>::preorder(NODE &t)
{
if(t!=NULL)
{
cout<<t->data<<" ";
preorder(t->left);
preorder(t->right);
}
}
template<class T>
void BST<T>::postorder(NODE &t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
cout<<t->data<<" ";
}
}
void menu()
{
cout<<"\nBinary Search Tree\n";
cout<<"-------------------\n";
cout<<"1.Insertion\n";
cout<<"2.Deletion\n";
cout<<"3.Find\n";
cout<<"4.Find Min\n";
cout<<"5.Find Max\n";
cout<<"6.Inorder Traversal\n";
cout<<"7.Preorder Traversal\n";
cout<<"8.Postorder Traversal\n";
cout<<"0.Exit\n";
}
void main()
{
clrscr();
BST<int>bst;
int ch,x,key;
NODE root=NULL;
NODE min,max;
do
{
menu();
cout<<"\nEnter your choice:";
cin>>ch;
switch(ch)
{
case 1: cout<<"\nInserting Element:";
cin>>x;
bst.insert_BST(x,root);
cout<<"\nInorder Traversal\n";
bst.inorder(root);
break;
case 2: cout<<"\nElement to delete:";
cin>>x;
bst.delete_BST(x,root);
cout<<"\nInorder Traversal after deletion\n";
bst.inorder(root);
break;
case 3: cout<<"\n Enter the element to be searched:";
cin>>key;
bst.Find(key,root);
break;
case 4: cout<<"\nMinimum element";
min=bst.Find_MIN(root);
cout<<min->data;
break;
case 5: cout<<"\nMaximum element";
max=bst.Find_MAX(root);
cout<<max->data;
break;
case 6: if(root==NULL)
cout<<"Empty Tree\n";
else
{
cout<<"\nRecursive Inorder:\n";
bst.inorder(root);
}
break;
case 7: if(root==NULL)
cout<<"Empty Tree\n";
else
{
cout<<"\nRecursive Preorder:\n";
bst.preorder(root);
}
break;
case 8: if(root==NULL)
cout<<"Empty Tree\n";
else
{
cout<<"\nRecursive Postorder:\n";
bst.postorder(root);
}
break;
case 0: exit(0);
default: cout<<"Enter Right Choice!!!\n";
}
}while(1);
}
OUTPUT:
Binary Search Tree
-------------------
1.Insertion
2.Deletion
3.Find
4.Find Min
5.Find Max
6.Inorder Traversal
7.Preorder Traversal
8.Postorder Traversal
0.Exit

Enter your choice:1


Inserting Element:33
Inorder Traversal
33
Binary Search Tree
-------------------
1.Insertion
2.Deletion
3.Find
4.Find Min
5.Find Max
6.Inorder Traversal
7.Preorder Traversal
8.Postorder Traversal
0.Exit

Enter your choice:1


Inserting Element:143
Inorder Traversal
33 143
Binary Search Tree
-------------------
1.Insertion
2.Deletion
3.Find
4.Find Min
5.Find Max
6.Inorder Traversal
7.Preorder Traversal
8.Postorder Traversal
0.Exit
Enter your choice:1
Inserting Element:50
Inorder Traversal
33 50 143
Binary Search Tree
-------------------
1.Insertion
2.Deletion
3.Find
4.Find Min
5.Find Max
6.Inorder Traversal
7.Preorder Traversal
8.Postorder Traversal
0.Exit

Enter your choice:4


Enter your choice:4
Minimum element33
Binary Search Tree
-------------------
1.Insertion
2.Deletion
3.Find
4.Find Min
5.Find Max
6.Inorder Traversal
7.Preorder Traversal
8.Postorder Traversal
0.Exit
Enter your choice:7
Recursive Preorder:
33 143 50
Binary Search Tree
-------------------
1.Insertion
2.Deletion
3.Find
4.Find Min
5.Find Max
6.Inorder Traversal
7.Preorder Traversal
8.Postorder Traversal
0.Exit

Enter your choice:0

4. Aim: Write a C++ program to perform the following operations on AVL-trees:


a) Insertion. b) Deletion.
Source Code:
#include<iostream>
#include<stdlib.h>
using namespace std;
#define TRUE 1
#define FALSE 0
#define NULL 0
class AVL;
class AVLNODE
{
friend class AVL;
private:
int data;
AVLNODE *left,*right;
int bf;
};
class AVL
{
private:
AVLNODE *root;
public:
AVLNODE *loc,*par;
AVL()
{
root=NULL;
}
int insert(int);
void displayitem();
void display(AVLNODE *);
void removeitem(int);
void remove1(AVLNODE *,AVLNODE *,int);
void remove2(AVLNODE *,AVLNODE *,int);
void search(int x);
void search1(AVLNODE *,int);
};
int AVL::insert(int x)
{
AVLNODE *a,*b,*c,*f,*p,*q,*y,*clchild,*crchild;
int found,unbalanced;
int d;
if(!root) //special case empty tree
{ y=new AVLNODE;
y->data=x;
root=y;
root->bf=0;
root->left=root->right=NULL;
return TRUE; }
//phase 1:locate insertion point for x.a keeps track of the most
// recent node with balance factor +/-1,and f is the parent of a
// q follows p through the tree.
f=NULL;
a=p=root;
q=NULL;
found=FALSE;
while(p&&!found)
{ //search for insertion point for x
if(p->bf)
{
a=p;
f=q;
}
if(x<p->data) //take left branch
{
q=p;
p=p->left;
}
else if(x>p->data)
{
q=p;
p=p->right;
}
else
{
y=p;
found=TRUE;
}
} //end while
//phase 2:insert and rebalance.x is not in the tree and
// may be inserted as the appropriate child of q.
if(!found)
{
y = new AVLNODE;
y->data=x;
y->left=y->right=NULL;
y->bf=0;
if(x<q->data) //insert as left child
q->left=y;
else
q->right=y; //insert as right child
//adjust balance factors of nodes on path from a to q
//note that by the definition of a,all nodes on this
//path must have balance factors of 0 and so will change
//to +/- d=+1 implies that x is inserted in the left
// subtree of a d=-1 implies
//to that x inserted in the right subtree of a.
if(x>a->data)
{
p=a->right;
b=p;
d=-1;
}
else
{
p=a->left;
b=p;
d=1;
}
while(p!=y)
if(x>p->data) //height of right increases by 1
{
p->bf=-1;
p=p->right;
}
else //height of left increases by 1
{
p->bf=1;
p=p->left;
}
//is tree unbalanced
unbalanced=TRUE;
if(!(a->bf)||!(a->bf+d))
{ //tree still balanced
a->bf+=d;
unbalanced=FALSE;
}
if(unbalanced) //tree unbalanced,determine rotation type
{
if(d==1)
{ //left imbalance
if(b->bf==1) //rotation type LL
{
a->left=b->right;
b->right=a;
a->bf=0;
b->bf=0;
}
else //rotation type LR
{
c=b->right;
b->right=c->left;
a->left=c->right;
c->left=b;
c->right=a;

switch(c->bf)
{
case 1: a->bf=-1; //LR(b)
b->bf=0;
break;
case -1:b->bf=1; //LR(c)
a->bf=0;
break;
case 0: b->bf=0; //LR(a)
a->bf=0;
break;
}
c->bf=0;
b=c; //b is the new root
} //end of LR
} //end of left imbalance
else //right imbalance
{
if(b->bf==-1) //rotation type RR
{
a->right=b->left;
b->left=a;
a->bf=0;
b->bf=0;
}
else //rotation type LR
{
c=b->right;
b->right=c->left;
a->right=c->left;
c->right=b;
c->left=a;
switch(c->bf)
{
case 1: a->bf=-1; //LR(b)
b->bf=0;
break;
case -1:b->bf=1; //LR(c)
a->bf=0;
break;
case 0: b->bf=0; //LR(a)
a->bf=0;
break;
}
c->bf=0;
b=c; //b is the new root
} //end of LR
}
//subtree with root b has been rebalanced and is the new subtree

if(!f)
root=b;
else if(a==f->left)
f->left=b;
else if(a==f->right)
f->right=b;
} //end of if unbalanced
return TRUE;
} //end of if(!found)
return FALSE;
} //end of AVL INSERTION

void AVL::displayitem()
{
display(root);
}
void AVL::display(AVLNODE *temp)
{
if(temp==NULL)
return;
cout<<temp->data<<" ";
display(temp->left);
display(temp->right);
}
void AVL::removeitem(int x)
{
search(x);
if(loc==NULL)
{
cout<<"\nitem is not in tree";
return;
}
if(loc->right!=NULL&&loc->left!=NULL)
remove1(loc,par,x);
else
remove2(loc,par,x);
}
void AVL::remove1(AVLNODE *l,AVLNODE *p,int x)
{
AVLNODE *ptr,*save,*suc,*psuc;
ptr=l->right;
save=l;
while(ptr->left!=NULL)
{
save=ptr;
ptr=ptr->left;
}
suc=ptr;
psuc=save;
remove2(suc,psuc,x);
if(p!=NULL)
if(l==p->left)
p->left=suc;
else
p->right=suc;
else
root=l;
suc->left=l->left;
suc->right=l->right;
return;
}
void AVL::remove2(AVLNODE *s,AVLNODE *p,int x)
{
AVLNODE *child;
if(s->left==NULL && s->right==NULL)
child=NULL;
else if(s->left!=NULL)
child=s->left;
else
child=s->right;
if(p!=NULL)
if(s==p->left)
p->left=child;
else
p->right=child;
else
root=child;

}
void AVL::search(int x)
{
search1(root,x);
}
void AVL::search1(AVLNODE *temp,int x)
{
AVLNODE *ptr,*save;
int flag;
if(temp==NULL)
{
cout<<"\nthe tree is empty";
return;
}
if(temp->data==x)
{
cout<<"\nthe item is root and is found";
par=NULL;
loc=temp;
par->left=NULL;
par->right=NULL;
return; }
if( x < temp->data)
{
ptr=temp->left;
save=temp;
}
else
{
ptr=temp->right;
save=temp;
}
while(ptr!=NULL)
{
if(x==ptr->data)
{ flag=1;
cout<<"\nitemfound";
loc=ptr;
par=save;

}
if(x<ptr->data)
ptr=ptr->left;
else
ptr=ptr->right;
}
if(flag!=1)
{
cout<<"item is not there in tree";
loc=NULL;
par=NULL;
cout<<loc;
cout<<par;
}
}
main()
{
AVL a;
int x,y,c;
char ch;
do
{
cout<<"\n1.insert";
cout<<"\n2.display";
cout<<"\n3.delete";
cout<<"\n4.search";
cout<<"\n5.exit";
cout<<"\nEnter u r choice to perform on AVL tree";
cin>>c;
switch(c)
{
case 1:cout<<"\nEnter an element to insert into tree";
cin>>x;
a.insert(x);
break;
case 2:a.displayitem(); break;
case 3:cout<<"\nEnter an item to deletion";
cin>>y;
a.removeitem(y);
break;
case 4:cout<<"\nEnter an element to search";
cin>>c;
a.search(c);
break;
case 5:exit(0); break;
default :cout<<"\nInvalid option try again";
}
cout<<"\ndo u want to continue";
cin>>ch;
}
while(ch=='y'||ch=='Y');
}
OUTPUT:
1.insert 2.display 3.delete 4.search 5.exit
Enter u r choice to perform on AVL tree1
Enter an element to insert into tree4

do u want to continue y

1.insert 2.display 3.delete 4.search 5.exit


Enter u r choice to perform on AVL tree1
Enter an element to insert into tree5

do u want to continue y

1.insert 2.display 3.delete 4.search 5.exit


Enter u r choice to perform on AVL tree3

Enter an item to deletion5

Item found
do u want to continue y

1.insert 2.display 3.delete 4.search 5.exit


Enter u r choice to perform on AVL tree2
4
do u want to continue n
5. Aim: Write a Program to implement dictionary ADT(quadratic probing)
Source Code:
#include<iostream.h>
#include<conio.h>
template<class T>
class QuadProbe
{
T bucket[11];
T num;
T key;
public:
QuadProbe();
void QuadDisp();
//~QuadProbe();
};
template<class T>
void QuadProbe<T>::QuadProbe()
{
T i,j,num;
for(i=0;i<11;i++)
bucket[i]=0;
while(1)
{
cout<<"\nInsert Element(Enter -1 to stop): ";
cin>>num;
if(num==-1)
break;
key=num%11;
if(bucket[key]==0)
bucket[key]=num;
else
{
i=1;
j=key;
while(bucket[j]!=0)
{
j=((key+i*i)%11);
i++;
}
if(bucket[j]==0)
bucket[j]=num;
}
}
}
template<class T>
void QuadProbe<T>::QuadDisp()
{
for(int i=0;i<11;i++)
cout<<"Key="<<i<<" "<<"Element="<<bucket[i]<<"\n";
}
void main()
{
clrscr();
QuadProbe<int>q;
cout<<"\nElements in the Quadratic Probe...\n\n";
q.QuadDisp();
getch();
}
OUTPUT:
Insert Element(Enter -1 to stop): 9
Insert Element(Enter -1 to stop): 10
Insert Element(Enter -1 to stop): 2
Insert Element(Enter -1 to stop): 50
Insert Element(Enter -1 to stop): 33
Insert Element(Enter -1 to stop): 99
Insert Element(Enter -1 to stop): 143
Insert Element(Enter -1 to stop): 141
Insert Element(Enter -1 to stop): 29
Insert Element(Enter -1 to stop): 256
Insert Element(Enter -1 to stop): -1
Elements in the Quadratic Probe...
Key=0 Element=33
Key=1 Element=99
Key=2 Element=2
Key=3 Element=256
Key=4 Element=143
Key=5 Element=0
Key=6 Element=50
Key=7 Element=141
Key=8 Element=29
Key=9 Element=9
Key=10 Element=10
PART-B
1. a) AIM : Queries using Aggregate Functions : COUNT, SUM, AVG, MIN, MAX and
GROUP BY, HAVING.
Source Code:
1] Find the number of rows in the EMP table.

SQL> SELECT COUNT ( * ) FROM EMP;

COUNT( * )
---------------
14

2] List the number of Jobs.

SQL> SELECT COUNT ( DISTINCT(JOB) ) AS TOTALJOBS FROM EMP;

TOTALJOBS
-----------------
5

3] Find the total salary of EMP table.

SQL> SELECT SUM(SAL) AS TOTALSALARY FROM EMP;

TOTALSALARY
----------------------
29025

4] List maximum salary, minimum salary, average salary of EMP table.


SQL> SELECT MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP;

MAX(SAL) MIN(SAL) AVG(SAL)


------------------------------------------------------
5000 800 2073.21429

5] List the number of people and average salary in DEPTNO 30.


SQL> SELECT COUNT( * ), AVG(SAL) FROM EMP WHERE DEPTNO = 30;

COUNT(*) AVG(SAL)
-----------------------------------
6 1566.66667

6] List maximum salary & minimum salary in the designations Salesman & Clerk.
SQL> SELECT COUNT(*), MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP WHERE
JOB IN ( 'SALESMAN', 'CLERK' );

COUNT(*) MAX(SAL) MIN(SAL) AVG(SAL)


--------------------------------------------------------------------------
8 1600 800 1218.7
7] Calculate total salary bill for each department.
SQL> SELECT DEPTNO, SUM(SAL) AS TOTALSAL FROM EMP GROUP BY
DEPTNO;

DEPTNO TOTALSAL
-----------------------------------
10 8750
20 10875
30 9400

8] List maximum salary, minimum salary & average salary of departments 10, 30.
SQL> SELECT DEPTNO, MIN(SAL), MAX(SAL), AVG(SAL) FROM EMP WHERE
DEPTNO IN (10, 30) GROUP BY DEPTNO;

DEPTNO MIN(SAL) MAX(SAL) AVG(SAL)


-------------------------------------------------------------------------
10 1300 5000 2916.66667
30 950 2850 1566.66667

9] Find all departments which are having more than 3 employees.


SQL> SELECT DEPTNO, COUNT(*) FROM EMP GROUP BY DEPTNO HAVING
COUNT(*) > 3;

DEPTNO COUNT(*)
----------------------------------
20 5
30 6

10] Display the jobs where the minimum salary is greater than or equal to 3000.
SQL> SELECT JOB, MIN(SAL) FROM EMP GROUP BY JOB HAVING
MIN(SAL) >= 3000;

JOB MIN(SAL)
-----------------------------------
ANALYST 3000
PRESIDENT 5000

1 . b) AIM : Creating & Dropping VIEWS.


Source Code:
1] Create a View that will store employee number, name, job, salary & department number
of all employees.

SQL> CREATE OR REPLACE VIEW EMP1


AS
SELECT EMPNO, ENAME, JOB, SAL, DEPTNO FROM EMP;

VIEW CREATED.

2] Create a View that will store the information of all employees who are working in
Dallas.
SQL> CREATE OR REPLACE VIEW EMP_DALLAS
AS
SELECT * FROM EMP WHERE DEPTNO = ( SELECT DEPTNO FROM DEPT
WHERE LOC = 'DALLAS' );

VIEW CREATED.

3] Drop the View EMP1 that is created from the EMP table.
SQL> DROP VIEW EMP1;

VIEW DROPPED.
2. a) AIM : Queries using conversion functions ( To_char, To_number, To_date ).
Source Code:
1] Display the names and hiredates of the employees of DEPTNO 20. Format of hiredate
as ‘12/03/84’

SQL> SELECT ENAME, TO_CHAR ( HIREDATE, 'DD/MM/YY' ) AS HIREDATE


FROM EMP WHERE DEPTNO = 20;

ENAME HIREDATE
-----------------------------------
SMITH 17/12/80
JONES 02/04/81
SCOTT 19/04/87
ADAMS 23/05/87
FORD 03/12/81

2] Display empno, employee name, job, salary of the employees. Show the salary with thousand
separator.

SQL> SELECT EMPNO, ENAME, JOB, TO_CHAR ( SAL, '$9,999' ) AS SALARY


FROM EMP;

EMPNO ENAME JOB SALARY


-----------------------------------------------------------------------
7369 SMITH CLERK $800
7499 ALLEN SALESMAN $1,600
7521 WARD SALESMAN $1,250
7566 JONES MANAGER $2,975
7654 MARTIN SALESMAN $1,250
7698 BLAKE MANAGER $2,850
7782 CLARK MANAGER $2,450
7788 SCOTT ANALYST $3,000
7839 KING PRESIDENT $5,000
7844 TURNER SALESMAN $1,500
7876 ADAMS CLERK $1,100
7900 JAMES CLERK $950
7902 FORD ANALYST $3,000
7934 MILLER CLERK $1,300

14 ROWS SELECTED.

3] List number of employees joined year wise.

SQL> SELECT TO_CHAR ( HIREDATE, 'YY' ) AS YY, COUNT(*) FROM EMP


GROUP BY TO_CHAR ( HIREDATE, 'YY' );

YY COUNT(*)
---------------------------------
80 1
81 10
82 1
87 2

4] List the employees who have joined between Apr 81 & Apr 82.

SQL> SELECT ENAME, TO_CHAR ( HIREDATE, 'MON YY' ) AS HIREDATE FROM


EMP WHERE TO_DATE ( HIREDATE ) BETWEEN TO_DATE ('01-APR-81')
AND TO_DATE('30-APR-82');

ENAME HIREDATE
----------------------------------
JONES APR 81
MARTIN SEP 81
BLAKE MAY 81
CLARK JUN 81
KING NOV 81
TURNER SEP 81
JAMES DEC 81
FORD DEC 81
MILLER JAN 82

9 ROWS SELECTED.

5] Add ‘100.00’ to the salary of every employee in EMP table.

SQL> SELECT ENAME, SAL + TO_NUMBER ( '100.00' ) AS SALARY FROM EMP;

ENAME SALARY
-----------------------------
SMITH 900
ALLEN 1700
WARD 1350
JONES 3075
MARTIN 1350
BLAKE 2950
CLARK 2550
SCOTT 3100
KING 5100
TURNER 1600
ADAMS 1200
JAMES 1050
FORD 3100
MILLER 1400
14 ROWS SELECTED.

2. b) AIM : Queries using String Functions : Concatenation, LPAD, RPAD, LTRIM,


RTRIM, LOWER, UPPER, INITCAP, LENGTH, SUBSTR and INSTR.
Source Code:
1] Display the output for all departments in the following manner:
Department number 10 with name Accounting is situated in Newyork.
SQL> SELECT 'Department number' | | DEPTNO | | 'with name' | | Initcap ( DNAME ) | |
'is situated in' | | Initcap ( LOC ) AS CONCATENATEDSTRING FROM DEPT;

CONCATENATEDSTRING
----------------------------------------------------------------------------------------
Department number 10 with name Accounting is situated in Newyork.
Department number 20 with name Research is situated in Dallas.
Department number 30 with name Sales is situated in Chicago.
Department number 40 with name Operations is situated in Boston.

2] Display ‘*’s before the employee names.

SQL> SELECT LPAD ( ENAME, 9 , '*' ) FROM EMP;

LPAD(ENAM
------------------
****SMITH
****ALLEN
*****WARD
****JONES
***MARTIN
****BLAKE
****CLARK
****SCOTT
*****KING
***TURNER
****ADAMS
****JAMES
*****FORD
***MILLER

14 ROWS SELECTED.

3] Display ‘*’s after the employee names.

SQL> SELECT RPAD ( ENAME, 9, '*' ) FROM EMP;

RPAD(ENAM
------------------
SMITH****
ALLEN****
WARD*****
JONES****
MARTIN***
BLAKE****
CLARK****
SCOTT****
KING*****
TURNER***
ADAMS****
JAMES****
FORD*****
MILLER***

14 ROWS SELECTED.

4] Lefttrim of Character ‘S’ from employee names of department number 20.

SQL> SELECT LTRIM ( ENAME, 'S' ) FROM EMP WHERE DEPTNO = 20;

LTRIM(ENA
-----------------
MITH
JONES
COTT
ADAMS
FORD

5] Righttrim of Character ‘S’ from employee names of department number 20.

SQL> SELECT RTRIM ( ENAME, 'S' ) FROM EMP WHERE DEPTNO = 20;

RTRIM(ENA
-----------------
SMITH
JONE
SCOTT
ADAM
FORD

6] List the employee names with all capital letters, with all small letters & with first letter
only as capital of department number 10.

SQL> SELECT ENAME, UPPER(ENAME), LOWER(ENAME), INITCAP(ENAME)


FROM EMP WHERE DEPTNO = 10;

ENAME UPPER(ENA LOWER(ENA INITCAP(E


------------------------------------------------------------------------------------------------
CLARK CLARK clark Clark
KING KING king King
MILLER MILLER miller Miller

7] List the employee names with length of the name sorted on length for department
number 30.

SQL> SELECT ENAME, LENGTH(ENAME) FROM EMP WHERE DEPTNO = 30


ORDER BY LENGTH(ENAME) ;

ENAME LENGTH(ENAME)
-----------------------------------------------
WARD 4
ALLEN 5
BLAKE 5
JAMES 5
MARTIN 6
TURNER 6

6 ROWS SELECTED.

8] Display the first four letters of job of EMP table.

SQL> SELECT DISTINCT ( SUBSTR(JOB, 1, 4) ) AS JOB FROM EMP;

JOB
----------
ANAL
CLER
MANA
PRES
SALE

5 ROWS SELECTED.

9] Display the ename & return the position of character ‘S’ in ENAME in DEPTNO 20.

SQL> SELECT ENAME, INSTR( ENAME, 'S' ) FROM EMP WHERE DEPTNO = 20;

ENAME INSTR(ENAME,'S')
-----------------------------------------------
SMITH 1
JONES 5
SCOTT 1
ADAMS 5
FORD 0

2. c) AIM : Queries using Date Functions : Sysdate, next_day, add_months, last_day,


months_between, least, greatest, trunk, round, to_char, to_date.
Source Code:
1] List the employee names having an experience more than 24 years.

SQL> SELECT ENAME, ROUND ( MONTHS_BETWEEN (SYSDATE, HIREDATE) /12 )


EXP FROM EMP WHERE ROUND ( MONTHS_BETWEEN (SYSDATE,
HIREDATE) /12 ) > 24;

ENAME EXP
----------------------------
SMITH 29
ALLEN 29
WARD 29
JONES 29
MARTIN 28
BLAKE 29
CLARK 29
KING 28
TURNER 28
JAMES 28
FORD 28
MILLER 28

12 ROWS SELECTED.

2] Find the first ‘SUN’day of employees after join in the organization of EMP table.

SQL> SELECT NEXT_DAY ( HIREDATE, 'SUN' ) AS HOLIDAY FROM EMP;

HOLIDAY
---------------
21-DEC-80
22-FEB-81
01-MAR-81
05-APR-81
04-OCT-81
03-MAY-81
14-JUN-81
26-APR-87
22-NOV-81
13-SEP-81
24-MAY-87
06-DEC-81
06-DEC-81
24-JAN-82

14 ROWS SELECTED.
3] Display hiredate & review date from EMP table, consider review date AS 1 year from
the hiredate for the DEPTNO 20.

SQL> SELECT HIREDATE, ADD_MONTHS ( HIREDATE, 12 ) AS REVIEWDATE


FROM EMP WHERE DEPTNO = 20;

HIREDATE REVIEWDATE
----------------------------------------
17-DEC-80 17-DEC-81
02-APR-81 02-APR-82
19-APR-87 19-APR-88
23-MAY-87 23-MAY-88
03-DEC-81 03-DEC-82

4] Display the last day of joining month of employees of DEPTNO 10 from EMP table.

SQL> SELECT HIREDATE, LAST_DAY ( HIREDATE ) AS LASTDAY FROM EMP


WHERE DEPTNO = 10;

HIREDATE LASTDAY
-------------------------------------
09-JUN-81 30-JUN-81
17-NOV-81 30-NOV-81
23-JAN-82 31-JAN-82

5] Find the least value of the following series :


9, 3, 56, 89, 23, 1, 0, -2, 12, 34, 9, 22

SQL> SELECT LEAST ( 9, 3, 56, 89, 23, 1, 0, -2, 12, 34, 9, 22) AS LOWEST FROM
DUAL;

LOWEST
-------------
-2

6] Find the greatest value of the following series :


9, 3, 56, 89, 23, 1, 0, -2, 12, 34, 9, 22

SQL> SELECT GREATEST ( 9, 3, 56, 89, 23, 1, 0, -2, 12, 34, 9, 22 ) AS HIGHEST FROM
DUAL;

HIGHEST
-------------
89

7] Trunc of the number 567.231656 by 3.

SQL> SELECT TRUNC ( 567.231656, 3 ) FROM DUAL;

TRUNC(567.231656, 3)
----------------------------
567.23

3.AIM : Program development using creation of procedures, passing parameters IN


and OUT of PROCEDURES.
Source Code:
SQL> CREATE OR REPLACE PROCEDURE P_EMPDEPT1 ( DEPTNO IN
NUMBER ) IS DUMMYDEPT NUMBER;

BEGIN
SELECT DISTINCT DEPTNO INTO DUMMYDEPT FROM EMP
WHERE DEPTNO = DEPNO;
DBMS_OUTPUT.PUT_LINE( ‘ HAI ’);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE( ‘ BYE ’);
END;
/
PROCEDURE CREATED.

SQL> EDIT P8.SQL


DECLARE
VALEXIST NUMBER(1);
DEPT NUMBER;
BEGIN
DEPT := &DEPT;
P_EMPDEPT1(DEPT);
END;

Result :
SQL> @P8.SQL
ENTER VALUE FOR DEPT : 20
OLD 5 : DEPT := &DEPT;
NEW 5 : DEPT := 20;
HAI
PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.

SQL> @P8.SQL
ENTER VALUE FOR DEPT : 50
OLD 5 : DEPT := &DEPT;
NEW 5 : DEPT := 50;
BYE
PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.

4.AIM : To develop a program using creation of Package specification, package


bodies, private objects, package variables and cursors and Calling stored
Packages.
Source Code:
PACKAGE SPECIFICATION :

SQL> CREATE OR REPLACE PACKAGE PCK_DEL IS PROCEDURE


P_EMPDEPT1(DEPTNO NUMBER);

END PCK_DEL
/
PACKAGE CREATED.

PACKAGE BODY :

SQL> CREATE OR REPLACE PACKAGE BODY PCK_DEL IS PROCEDURE


P_EMPDEPT1(DEPNO IN NUMBER) IS DUMMYDEPT NUMBER;

BEGIN
SELECT DISTINCT DEPTNO INTO DUMMYDEPT FROM EMP
WHERE DEPTNO = DEPNO;
DBMS_OUTPUT.PUT_LINE( ‘DEPT NUMBER IS PRESENT’);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE( ‘ DEPT NUMBER IS NOT
PRESENT’);
END;
END PCK_DEL;
/
Result :
SQL> EXECUTE PCK_DEL.P_EMPDEPT1(10);
DEPT NUMBER IS PRESENT

PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.

SQL> EXECUTE PCK_DEL.P_EMPDEPT1(50);


DEPT NUMBER IS NOT PRESENT

PL/SQL PROCEDURE SUCCESSFULLY COMPLETED.

5.AIM : To develop a program using features parameter in a CURSOR, FOR


UPDATE CURSOR, WHERE CURRENT of clause and CURSOR variables.
Source Code:
SQL> EDIT P11.SQL

DECLARE
SALARY EMP.SAL%TYPE;
S NUMBER := 0;
CURSOR C1 IS SELECT SAL FROM EMP;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO SALARY;
S := S+SALARY;
EXIT WHEN C1 % NOTFOUND;
UPDATE EMP SET SAL = SAL + SAL * 10/100
WHERE DEPTNO = 20 AND DEPTNO = 40;
END LOOP;
DBMS_OUTPUT.PUT_LINE( ‘ TOTAL IS : ’);
DBMS_OUTPUT.PUT_LINE( TO_CHAR(S) );
CLOSE C1;
END;

Result :
SQL> @P11.SQL
TOTAL IS :
30325

6.AIM : To Develop programs using BEFORE & AFTER Triggers, Row & Statement Triggers.
Source Code:
SQL> CREATE TABLE CLIENT_MASTER ( CLIENTNO VARCHAR2(10), NAME
VARCHAR2(20), BAL_DUE NUMBER(10, 2), ADDRESS VARCHAR2(15),
CITY VARCHAR2(20) );
TABLE CREATED.

SQL> CREATE TABLE AUDIT_CLIENT ( CLIENTNO VARCHAR2(10), NAME


VARCHAR2(20), BAL_DUE NUMBER(10, 2), OPERATION
VARCHAR2(10), USERID VARCHAR2(10), ODATE DATE );

TABLE CREATED.

SQL> INSERT INTO CLIENT_MASTER VALUES ( 1000, ‘XYZ’, 50, ‘SACET’,


‘CHIRALA’ );

1 ROW INSERTED.

SQL> INSERT INTO CLIENT_MASTER VALUES ( 2000, ‘ABC’, 100, ‘SAEC’,


‘CHIRALA’ );

1 ROW INSERTED.

SQL> SELECT * FROM CLIENT_MASTER ;

CLIENTNO NAME BAL_DUE ADDRESS CITY


--------------------------------------------------------------------------------------------------
1000 XYZ 50 SACET CHIRALA
2000 ABC 100 SAEC CHIRALA

2 ROWS SELECTED.

SQL> SELECT * FROM AUDIT_CLIENT ;

NO ROWS SELECTED.

BEFORE

SQL> EDIT TRIGGER1.SQL

CREATE OR REPLACE TRIGGER AUDIT_TRAIL BEFORE UPDATE


ON CLIENT_MASTER FOR EACH ROW;
DECLARE
OPER VARCHAR2(10);
CLIENTNO CLIENT_MASTER.CLIENTNO % TYPE;
NAME CLIENT_MASTER.NAME % TYPE;
BAL_DUE CLIENT_MASTER.BAL_DUE % TYPE;
BEGIN
IF UPDATING THEN
OPER := ‘UPDATE’ ;
END IF;
IF DELETING THEN
OPER := ‘DELETE’;
END IF;
CLIENTNO :=: OLD.CLIENTNO;
NAME :=: OLD.NAME;
BAL_DUE :=. OLD.BAL_DUE;
INSERT INTO AUDIT_CLIENT VALUES ( CLIENTNO, NAME,
BAL_DUE, OPER, USER, SYSDATE );
END;
/

SQL> @TRIGGER1.SQL

TRIGGER CREATED.

SQL> UPDATE CLIENT_MASTER SET CLIENTNO = 2500 WHERE


CLIENTNO = 1000;
1 ROW UPDATED.

SQL> SELECT * FROM CLIENT_MASTER ;

CLIENTNO NAME BAL_DUE ADDRESS CITY


--------------------------------------------------------------------------------------------------
2500 XYZ 50 SACET CHIRALA
2000 ABC 100 SAEC CHIRALA
2 ROWS SELECTED.

SQL> SELECT * FROM AUDIT_CLIENT ;

CLIENTNO NAME BAL_DUE OPERATION USERID ODATE


---------------------------------------------------------------------------------------------------------
1000 XYZ 50 UPDATE SCOTT 19 JAN 10
1 ROW SELECTED.

AFTER

SQL> EDIT TRIGGER2.SQL

CREATE OR REPLACE TRIGGER AUDIT_TRAIL1 AFTER DELETE


ON CLIENT_MASTER FOR EACH ROW;
DECLARE
OPER VARCHAR2(10);
CLIENTNO CLIENT_MASTER.CLIENTNO % TYPE;
NAME CLIENT_MASTER.NAME % TYPE;
BAL_DUE CLIENT_MASTER.BAL_DUE % TYPE;
BEGIN
IF UPDATING THEN
OPER := ‘UPDATE’ ;
END IF;
IF DELETING THEN
OPER := ‘DELETE’;
END IF;
CLIENTNO :=: OLD.CLIENTNO;
NAME :=: OLD.NAME;
BAL_DUE :=. OLD.BAL_DUE;
INSERT INTO AUDIT_CLIENT VALUES ( CLIENTNO, NAME,
BAL_DUE, OPER, USER, SYSDATE );
END;
/

SQL> @TRIGGER2.SQL

TRIGGER CREATED.

SQL> DELETE CLIENT_MASTER WHERE CLIENTNO = 2000;


1 ROW DELETED.

SQL> SELECT * FROM CLIENT_MASTER ;

CLIENTNO NAME BAL_DUE ADDRESS CITY


----------------------------------------------------------------------------------------------
2500 XYZ 50 SACET CHIRALA
1 ROW SELECTED.

SQL> SELECT * FROM AUDIT_CLIENT ;

CLIENTNO NAME BAL_DUE OPERATION USERID ODATE


------------------------------------------------------------------------------------------------------
2000 ABC 100 DELETE SCOTT 19 JAN 10
1000 XYZ 50 UPDATE SCOTT 19 JAN 10

2 ROWS SELECTED
OS
1.AIM : PROGRAM TO CREATE A SEMAPHORE TO WRITE LOCK A FILE BY A
PROCESS.
Source code:
#inlcude<stdio.h>
#include<unistd.h>
#include<sys/sem.h>
#inlcude<sys/ipc.h>
#include<fcntl.h>
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
};
int main( )
{
int semid , fd, i, pid;
char fp[50], b[1];
union semun sval;
semid = semget( IPC_PRIVATE, 1, IPC_CREAT|0600);
if(semid == -1)
printf(“\n Sem Error………”);
else
printf(“\n SemID : %d”, semid);
printf(“\n\t Enter file path : ” );
scanf(“%s”,fp);
sval.val = -1;
fd = open(fp, O_RDWR);
printf(“\n\t Parent : Semaphore set for Write lock ” );
semctl(semid, 0, SETVAL, &sval);
pid = fork( );
if( pid == 0)
{
semctl( semid, 0, GETVAL, &sval);
if(sval.val == -1)
printf(“\n child:File protected by semaphore”);
}
sval.val=1;
semctl(semid,0,SETVAL,&sval);
printf(“\n parent: Released by the semaphore”);

if(pid==0)
{
semctl(semid,0,GETVAL,&sval);
if(sval.val==1)
printf(“\n child:semaphore released”);
else
printf(‘semaphore val:%d”,sval.val);
printf(“Data read:\n”);
while(read(fd,b,1))
printf(“%c”,b[0]);
}
}
Input:
sem id:524302
Enter file path:test.c
Output:
Parent:semaphore set for write lock
Child:File protected by semaphore
Parent: Released the semaphore
Child: semaphore is released
Data read:
#include<sys/msg.h>
#include<sys/ipc.h>
int main()
{
int mid,r;
char *x;
mid=msgget(IPC_PRIVATE,IPC_CREAT);
printf(“id:%d”,mid);
r=msgrcv(mid,&x,10,0,0);
printf(“val: %d”,r);
}
Parent: semaphore set for write lock
Parent: Released the semaphore
2.AIM : Write a program to provide shared lock and exclusive locks on a file by different
processes.
SOURCE CODE:
#include<unistd.h>
#include<fcntl.h>
int main()
{
int pid,fd,fd1;
struct flock lp={F_RDLCK,SEEK-SET,0,20,0};
struct flock ls ={F_RDLCK,SEEK_SET,0,40,0};
char m[50]=”file locking program”;
fd=open(“test”,O_RDWR|O_CREAT,07777);
write(fd,m,50);
printf(“\n parent(%d)->shared(read) lock”,getpid());
lp.l_pid=getpid();
if(fcntl(fd,F_SETLKW,&ip)==-1)
printf(“lock failed”);
else
{
printf(“\n lock success \n lock by:%d”,lp.l_pid);
printf(“\n form %d of length %d\n lock type:%d’,lp.l_start,lp.l_len,lp.l_type);
}
lp.l_type=F_WRLCK;
lp.l_start=21;
lp.l_len=20;
printf(“\n parent(%d)->exclusive(write) lock”,getpid());
if(fcntl(fd,F_SETLKW,&lp)==-1)
printf(“lock failed”);
else
{
printf(“\n lock success\n lock by:%d”,lp.l_pid);
printf(“\n form %d of length %d\n lock type:%d”,lp.l_start,lp.l_len,lp.l_type);
}
pid=fork();
if(pid==0)
{
printf(“\n\n child(%d):->exclusive(write)lock”,getpid());
lc.l_type=F_WRLCK;
lc.l_pid=getpid();
fcntl(fd,F_GETLK,&lc);
if(lc.l_pid==getpid())
printf(“\n child can acquire lock”);
else
printf(“already locked by:%d \n form %d of length %d\n lock
type:%d”,lc.l_pid,lc.l_start,lc.l_len,lc.l_type);
printf(“\n child(%d):->shared(read) lock”,getpid());
lc.l_type=F_RDLCK;
lc.l_pid=getpid();
fcntl(fd,f_GETLK,&lc);
if(lc.l_pid==getpid())
printf(“child can acquire lock”);
else
{
printf(“\n already locked by:%d\n form %d of lenget %d\n lock
type:%d”,lc.l_pid,lc.l_start,lc.l_len,lc.l_type);
}
}

OUTPUT:

Parent(5241)->shared(read) lock
Lock success
Locked by :5241
Form 0 of length 20
Lock type :0
Parent(5241)->exclusive(write) lock
Lock success
Locked by :5241
Form 21 of length 20
Lock type :1
child(5242)->Exclusive(write) lock
Already locked by:5241
Form 0 of length 20
Lock type :0
child(5242)->shared(read) lock
child can acquire lock
lock type:1
3.AIM: PROGRAM FOR ROUND ROBIN CPU SCHEDULING ALGORITHM
Source code:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<string.h>
void main()
{
char p[10][5];
int et[10],wt[10],timer=3,count,pt[10],rt,i,j,totwt=0,t,n=5,found=0,m;
float avgwt;
clrscr();
for(i=0;i<n;i++)
{
printf("enter the process name : ");
scanf("%s",&p[i]);
printf("enter the processing time : ");
scanf("%d",&pt[i]);
}
m=n;
wt[0]=0;
i=0;
do
{
if(pt[i]>timer)
{
rt=pt[i]-timer;
strcpy(p[n],p[i]);
pt[n]=rt;
et[i]=timer;
n++;
}
else
{
et[i]=pt[i];
}
i++;
wt[i]=wt[i-1]+et[i-1];
}while(i<n);
count=0;
for(i=0;i<m;i++)
{
for(j=i+1;j<=n;j++)
{
if(strcmp(p[i],p[j])==0)
{
count++;
found=j;
}
}
if(found!=0)
{

wt[i]=wt[found]-(count*timer);
count=0;
found=0;
}
}
for(i=0;i<m;i++)
{
totwt+=wt[i];
}
avgwt=(float)totwt/m;
for(i=0;i<m;i++)
{
printf("\n%s\t%d\t%d",p[i],pt[i],wt[i]);
}
printf("\ntotal waiting time %d\n",totwt);
printf("total avgtime %f",avgwt);
}
Input :
enter the process name : aaa
enter the processing time : 4
enter the process name : bbb
enter the processing time : 3
enter the process name : ccc
enter the processing time : 2
enter the process name : ddd
enter the processing time : 5
enter the process name : eee
enter the processing time : 1
Output :
p_name p_time w_time
aaa 4 9
bbb 3 3
ccc 2 6
ddd 5 10
eee 1 11
total waiting time : 39
average waiting time : 7.8000
4.AIM: PROGRAM FOR DEADLOCK DETECTION ALGORITHM
Source code:
#include<stdio.h>
#include<conio.h>
void main()
{
int found,flag,l,p[4][5],tp,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
printf("enter total no of processes");
scanf("%d",&tp);
printf("enter clain matrix");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
{
scanf("%d",&c[i][j]);
}
printf("enter allocation matrix");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
{
scanf("%d",&p[i][j]);
}
printf("enter resource vector:\n");
for(i=1;i<=5;i++)
{
scanf("%d",&r[i]);
}
printf("enter availability vector:\n");
for(i=1;i<=5;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=1;i<=4;i++)
{
sum=0;
for(j=1;j<=5;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=4;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=5;j++)
if(c[i][j]>temp[j])
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=5;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
getch();
}

Input:
enter total no. of processes : 4
enter claim matrix :
01001
00101
00001
10101
enter allocation matrix :
10110
11000
00010
00000
enter resource vector :
21121
enter the availability vector :
00001
Output :
deadlock causing processes are : 1 2

5.AIM:Program for paging technique in memory management


Source code:
#include<stdio.h>
#include<conio.h>
void main()
{
int ps,ms,np,nf,pt[20],I,page,offset,id,ph_add;
clrscr();
printf(“ \n Enter page size, memorysize, no of pages”);
scanf(“%d%d%d”,&ps,&ms,&np);
nf=ms/ps;
for(i=0;i<np;i++)
{
printf(“ \n Enter the size of local address”);
scanf(“%d”,&id);
page=id%ps;
ph_add=pt[page]*ps+offset;
printf(“ \n physical address is %d”,ph_add);
printf(“ \n no of frames+%d \n pages=%d \noffset%d”,nf,page,offset);
getch();
}
}
Output:
Enter page size, memory size, no of pages 5 2 2
Enter the size of logical address 10
Physical address is 18906
No of frames+0
Page=0
Offset=3240

You might also like