Download as pdf or txt
Download as pdf or txt
You are on page 1of 64

Name: Mehedi Hasan Moni

Admission Number: - 19SCSE1140001

B.tech CSE with CNCS , Sem: V

Course Code: -BTCS3550.

Course Name: -Technical Training (Lab)

Academic Year: -2021-22


1. To write a program for implementation of CPU
scheduling algorithms.

(a) SJF:-
Code:-

#include <iostream>
using namespace std;
int mat[10][6];

void swap(int* a, int* b)


{
int temp = *a;
*a = *b;
*b = temp;
}

void arrangeArrival(int num, int mat[][6])


{
for (int i = 0; i < num; i++) {
for (int j = 0; j < num - i - 1; j++) {
if (mat[j][1] > mat[j + 1][1]) {
for (int k = 0; k < 5; k++) {
swap(mat[j][k], mat[j + 1][k]);
}
}
}
}
}

void completionTime(int num, int mat[][6])


{
int temp, val;
mat[0][3] = mat[0][1] + mat[0][2];
mat[0][5] = mat[0][3] - mat[0][1];
mat[0][4] = mat[0][5] - mat[0][2];

for (int i = 1; i < num; i++) {


temp = mat[i - 1][3];
int low = mat[i][2];
for (int j = i; j < num; j++) {
if (temp >= mat[j][1] && low >= mat[j][2]) {
low = mat[j][2];
val = j;
}
}
mat[val][3] = temp + mat[val][2];
mat[val][5] = mat[val][3] - mat[val][1];
mat[val][4] = mat[val][5] - mat[val][2];
for (int k = 0; k < 6; k++) {
swap(mat[val][k], mat[i][k]);
}
}
}
int main()
{
int num, temp;

cout << "Enter number of Process: ";


cin >> num;

cout << "...Enter the process ID...\n";


for (int i = 0; i < num; i++) {
cout << "...Process " << i + 1 << "...\n";
cout << "Enter Process Id: ";
cin >> mat[i][0];
cout << "Enter Arrival Time: ";
cin >> mat[i][1];
cout << "Enter Burst Time: ";
cin >> mat[i][2];
}

cout << "Before Arrange...\n";


cout << "Process ID\tArrival Time\tBurst Time\n";
for (int i = 0; i < num; i++) {
cout << mat[i][0] << "\t\t" << mat[i][1] << "\t\t"
<< mat[i][2] << "\n";
}

arrangeArrival(num, mat);
completionTime(num, mat);
cout << "Final Result...\n";
cout << "Process ID\tArrival Time\tBurst Time\tWaiting "
"Time\tTurnaround Time\n";
for (int i = 0; i < num; i++) {
cout << mat[i][0] << "\t\t" << mat[i][1] << "\t\t"
<< mat[i][2] << "\t\t" << mat[i][4] << "\t\t"
<< mat[i][5] << "\n";
}
}

OUTPUT:-
(b) FCFS:-
Code:-

#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details


cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}
// Driver code
int main()
{

//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


int burst_time[] = {10, 5, 8};

findavgTime(processes, n, burst_time);
return 0;
}

OUTPUT:-

(c) PRIORITY:-
#include<bits/stdc++.h>
using namespace std;

struct Process
{
int pid; // Process ID
int bt; // CPU Burst time required
int priority; // Priority of this process
};

// Function to sort the Process acc. to priority


bool comparison(Process a, Process b)
{
return (a.priority > b.priority);
}

// Function to find the waiting time for all


// processes
void findWaitingTime(Process proc[], int n,
int wt[])
{
// waiting time for first process is 0
wt[0] = 0;
// calculating waiting time
for (int i = 1; i < n ; i++ )
wt[i] = proc[i-1].bt + wt[i-1] ;
}

// Function to calculate turn around time


void findTurnAroundTime( Process proc[], int n,
int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = proc[i].bt + wt[i];
}

//Function to calculate average time


void findavgTime(Process proc[], int n)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(proc, n, wt);

//Function to find turn around time for all processes


findTurnAroundTime(proc, n, wt, tat);

//Display processes along with all details


cout << "\nProcesses "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << proc[i].pid << "\t\t"
<< proc[i].bt << "\t " << wt[i]
<< "\t\t " << tat[i] <<endl;
}

cout << "\nAverage waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

void priorityScheduling(Process proc[], int n)


{
// Sort processes by priority
sort(proc, proc + n, comparison);

cout<< "Order in which processes gets executed \n";


for (int i = 0 ; i < n; i++)
cout << proc[i].pid <<" " ;

findavgTime(proc, n);
}
// Driver code
int main()
{
Process proc[] = {{1, 10, 2}, {2, 5, 0}, {3, 8, 1}};
int n = sizeof proc / sizeof proc[0];
priorityScheduling(proc, n);
return 0;
}

OUTPUT:-

(d) ROUND ROBIN:-


Code:-
// C++ program for implementation of RR scheduling
#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
{
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time

// Keep traversing processes in round robin manner


// until all of them are not done.
while (1)
{
bool done = true;

// Traverse all processes one by one repeatedly


for (int i = 0 ; i < n; i++)
{
// If burst time of a process is greater than 0
// then only need to process further
if (rem_bt[i] > 0)
{
done = false; // There is a pending process

if (rem_bt[i] > quantum)


{
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;

// Decrease the burst_time of current process


// by quantum
rem_bt[i] -= quantum;
}

// If burst time is smaller than or equal to


// quantum. Last cycle for this process
else
{
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];

// Waiting time is current time minus time


// used by this process
wt[i] = t - bt[i];

// As the process gets fully executed


// make its remaining burst time = 0
rem_bt[i] = 0;
}
}
}

// If all processes are done


if (done == true)
break;
}
}

// Function to calculate turn around time


void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

// Function to calculate average time


void findavgTime(int processes[], int n, int bt[],
int quantum)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
// Function to find waiting time of all processes
findWaitingTime(processes, n, bt, wt, quantum);

// Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

// Display processes along with all details


cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

// Driver code
int main()
{

int processes[] = { 1, 2, 3};


int n = sizeof processes / sizeof processes[0];

// Burst time of all processes


int burst_time[] = {10, 5, 8};

// Time quantum
int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}

OUTPUT:
(e) SRTF:-
Code:-

#include<iostream>

using namespace std;

int main()

int a[10],b[10],x[10];

int waiting[10],turnaround[10],completion[10];

int i,j,smallest,count=0,time,n;

double avg=0,tt=0,end;

cout<<"\nEnter the number of Processes: "; //input

cin>>n;

for(i=0; i<n; i++)

cout<<"\nEnter arrival time of process: "; //input

cin>>a[i];

for(i=0; i<n; i++)

cout<<"\nEnter burst time of process: "; //input

cin>>b[i];

for(i=0; i<n; i++)

x[i]=b[i];

b[9]=9999;

for(time=0; count!=n; time++)

smallest=9;
for(i=0; i<n; i++)

if(a[i]<=time && b[i]<b[smallest] && b[i]>0 )

smallest=i;

b[smallest]--;

if(b[smallest]==0)

count++;

end=time+1;

completion[smallest] = end;

waiting[smallest] = end - a[smallest] - x[smallest];

turnaround[smallest] = end - a[smallest];

cout<<"Process"<<"\t"<< "burst-time"<<"\t"<<"arrival-time" <<"\t"<<"waiting-time"


<<"\t"<<"turnaround-time"<< "\t"<<"completion-time"<<endl;

for(i=0; i<n; i++)

cout<<"p"<<i+1<<"\t\t"<<x[i]<<"\t\t"<<a[i]<<"\t\t"<<waiting[i]<<"\t\t"<<turnaround[i]<<"\t\t"<<
completion[i]<<endl;

avg = avg + waiting[i];

tt = tt + turnaround[i];

cout<<"\n\nAverage waiting time ="<<avg/n;

cout<<" Average Turnaround time ="<<tt/n<<endl;


} OUTPUT:-
2. To write a program to implement the producer-consumer
problem using semaphores.

Code:-

#include <stdio.h>
#include
<stdlib.h> int
mutex = 1;
int full = 0;
int empty = 10, x = 0;
void producer()
{
--mutex;
++full;
--empty;
x++;
printf("\nProducer produces""item %d",x);
++mutex;
}
void consumer()
{
--mutex;
--full;
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;
++mutex;
}
int main()
{
int n, i;
printf("\n1. Press 1 for Producer""\n2. Press 2 for Consumer""\n3. Press 3 for
Exit");#pragma omp critical

for (i = 1; i > 0; i++) {


printf("\nEnter your choice:");
scanf("%d", &n);
switch (n)
{case 1:
if ((mutex == 1)
&& (empty != 0)) {
producer();
}
else {
printf("Buffer is full!");
}
break;

case 2:
if ((mutex == 1)
&& (full != 0)) {
consumer();
}
else {
printf("Buffer is empty!");
}
break
;case 3:
exit(0);
break
;
}
}
}

OUTPUT:-
3. Write a program to implement stack andqueue data structure
using arrays and linked list with all the operations applicableon
these.

(a) STACK:-
Code:-

#include <bits/stdc++.h>

using namespace std;

#define MAX 1000

class Stack {
int top;

public:
int a[MAX]; // Maximum size of Stack

Stack() { top = -1; }


bool push(int x);
int pop();
int peek();
bool isEmpty();
};

bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
}

int Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
}
int Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}

bool Stack::isEmpty()
{
return (top < 0);
}

// Driver program to test above functions


int main()
{

class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
//print all elements in stack :
cout<<"Elements present in stack : ";
while(!s.isEmpty())
{
// print top element in stack
cout<<s.peek()<<" ";
// remove top element in stack
s.pop();
}

return 0;
}

OUTPUT:-

(b) QUEUE:-

queue=[]
def enqueue(element):
queue.append(element)

print("Element added in queue from rear:enqueue()-" ,element)


def isEmpty():
if len(queue)==0:
return True
else:
return False
def dequeue():
if isEmpty():
print("queue is empty")
return 0
else:
return queue.pop(0)
enqueue(10)
enqueue(20)
enqueue(45)
print("Queue:")
for k in queue:
print(" " ,k,end=' ')
print(' ')
result=dequeue()
print("Element removed from queue-dequeue():" ,result)

OUTPUT:-
4. Write a program to implement queueusing stack and stack
using queue data structures.

(a) Queue using Stack:-


Code:-

#include <bits/stdc++.h>
using namespace std;

struct Queue {
stack<int> s1, s2;

void enQueue(int x)
{
// Move all elements from s1 to s2
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}

// Push item into s1


s1.push(x);

// Push everything back to s1


while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
}

// Dequeue an item from the queue


int deQueue()
{
// if first stack is empty
if (s1.empty()) {
cout << "Q is Empty";
exit(0);
}

// Return top of s1
int x = s1.top();
s1.pop();
return x;
}
};

// Driver code
int main()
{

Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);

cout << q.deQueue() << '\n';


cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';

return 0;
}
OUTPUT:-

(b) Stack using Queue:-


Code:-

#include <bits/stdc++.h>

using namespace std;

class Stack {
// Two inbuilt queues
queue<int> q1, q2;

// To maintain current number of


// elements
int curr_size;

public:
Stack()
{
curr_size = 0;
}

void push(int x)
{
curr_size++;

// Push x first in empty q2


q2.push(x);

// Push all the remaining


// elements in q1 to q2.
while (!q1.empty()) {
q2.push(q1.front());
q1.pop();
}

// swap the names of two queues


queue<int> q = q1;
q1 = q2;
q2 = q;
}

void pop()
{

// if no elements are there in q1


if (q1.empty())
return;
q1.pop();
curr_size--;
}

int top()
{
if (q1.empty())
return -1;
return q1.front();
}

int size()
{
return curr_size;
}
};

// Driver code
int main()
{

Stack s;
s.push(1);
s.push(2);
s.push(3);

cout << "current size: " << s.size()


<< endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;

cout << "current size: " << s.size()


<< endl;
return 0;
}

OUTPUT:-
5. Write a program to implement linked list with

insertion,deletion,traversal,searching,and doubly linked list

operation.

(a) Traversing:-
Code:-

class Node:
'''This class is used for linked list'''
def _init_(self,value):
self.data=valu
e
self.next=Non
e
node_a=Node(10)
node_b=Node(20)
node_c=Node(45)
node_a.next=node_b
node_b.next=node_c
head=node_a
start=head
while start!=None:
print(start.data,'| next ------- >' ,end=' ')
start=start.nex
tprint('None')

OUTPUT:-
(b) Searching an element in a linked list:-Code:-

#include <bits/stdc++.h>
using namespace std;

/* Link list node */


class Node
{
public:
int key;
Node* next;
};

/* Given a reference (pointer to pointer) to the head


of a list and an int, push a new node on the front
of the list. */
void push(Node** head_ref, int new_key)
{
/* allocate node */
Node* new_node = new Node();

/* put in the key */


new_node->key = new_key;

/* link the old list off the new node */


new_node->next = (*head_ref);

/* move the head to point to the new node */


(*head_ref) = new_node;
}

/* Checks whether the value x is present in linked list */


bool search(Node* head, int x)
{
Node* current = head; // Initialize current
while (current != NULL)
{
if (current->key == x)
return true;
current = current->next;
}
return false;
}

/* Driver program to test count function*/


int main()
{

/* Start with the empty list */


Node* head = NULL;
int x = 21;

/* Use push() to construct below list


14->21->11->30->10 */
push(&head, 10);
push(&head, 30);
push(&head, 11);
push(&head, 21);
push(&head, 14);

search(head, 21)? cout<<"Yes" : cout<<"No";


return 0;
}
OUTPUT:-

(c) Inserting an element in a linked list:-


Code:-

#include <stdlib.h>

#include <iostream>
using namespace std;

// Create a node
struct Node {
int data;
struct Node* next;
};

void insertAtBeginning(struct Node** head_ref, int new_data) {


// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;
new_node->next = (*head_ref);

// Move head to new node


(*head_ref) = new_node;
}

// Insert a node after a node


void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

// Insert at the end


void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;
new_node->next = NULL;

if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

while (last->next != NULL) last = last->next;

last->next = new_node;
return;
}

// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {


*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;

// Remove the node


prev->next = temp->next;

free(temp);
}

// Search a node
bool searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;

while (current != NULL) {


if (current->data == key) return true;
current = current->next;
}
return false;
}

// Sort the linked list


void sortLinkedList(struct Node** head_ref) {
struct Node *current = *head_ref, *index = NULL;
int temp;

if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;

while (index != NULL) {


if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}

// Print the linked list


void printList(struct Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

// Driver program
int main() {

struct Node* head = NULL;

insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

cout << "Linked list: ";


printList(head);

cout << "\nAfter deleting an element: ";


deleteNode(&head, 3);
printList(head);

int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
cout << endl << item_to_find << " is found";
} else {
cout << endl << item_to_find << " is not found";
}

sortLinkedList(&head);
cout << "\nSorted List: ";
printList(head);
}
OUTPUT:-
(d) Deleting an element in a linked list:-
Code:-

#include <stdlib.h>

#include <iostream>
using namespace std;

// Create a node
struct Node {
int data;
struct Node* next;
};

void insertAtBeginning(struct Node** head_ref, int new_data) {


// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;
new_node->next = (*head_ref);

// Move head to new node


(*head_ref) = new_node;
}

// Insert a node after a node


void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

// Insert at the end


void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;
new_node->next = NULL;

if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

while (last->next != NULL) last = last->next;

last->next = new_node;
return;
}
// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {


*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;

// Remove the node


prev->next = temp->next;

free(temp);
}

// Search a node

// Print the linked list


void printList(struct Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

// Driver program
int main() {

struct Node* head = NULL;

insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

cout << "Linked list: ";


printList(head);

cout << "\nAfter deleting an element: ";


deleteNode(&head, 3);
printList(head);

OUTPUT:-
(e) Doubly Linked List:-
Code:-

class Node:

# Constructor to create a new node


def init (self, data):
self.data = data
self.next = None
self.prev = None

# Class to create a Doubly Linked List


class DoublyLinkedList:

# Constructor for empty Doubly Linked List


def init (self):
self.head = None

# Given a reference to the head of a list and an


# integer, inserts a new node on the front of list
def push(self, new_data):

# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)

# 3. Make next of new node as head and


# previous as None (already None)
new_node.next = self.head

# 4. change prev of head node to new_node


if self.head is not None:
self.head.prev = new_node

# 5. move the head to point to the new node


self.head = new_node

# Given a node as prev_node, insert a new node after


# the given node
def insertAfter(self, prev_node, new_data):

# 1. Check if the given prev_node is None


if prev_node is None:
print("the given previous node cannot be NULL")
return

# 2. allocate new node


# 3. put in the data
new_node = Node(new_data)

# 4. Make net of new node as next of prev node


new_node.next = prev_node.next

# 5. Make prev_node as previous of new_node


prev_node.next = new_node

# 6. Make prev_node ass previous of new_node


new_node.prev = prev_node

# 7. Change previous of new_nodes's next node


if new_node.next:
new_node.next.prev = new_node

# Given a reference to the head of DLL and integer,


# appends a new node at the end
def append(self, new_data):

# 1. Allocates node
# 2. Put in the data
new_node = Node(new_data)

# 3. This new node is going to be the last node,


# so make next of it as None
# (It already is initialized as None)

# 4. If the Linked List is empty, then make the


# new node as head
if self.head is None:
self.head = new_node
return

# 5. Else traverse till the last node


last = self.head
while last.next:
last = last.next

# 6. Change the next of last node


last.next = new_node

# 7. Make last node as previous of new node


new_node.prev = last

return

# This function prints contents of linked list


# starting from the given node
def printList(self, node):

print("\nTraversal in forward direction")


while node:
print(" {}".format(node.data))
last = node
node = node.next

print("\nTraversal in reverse direction")


while last:
print(" {}".format(last.data))
last = last.prev

# Driver program to test above functions

# Start with empty list


llist = DoublyLinkedList()

# Insert 6. So the list becomes 6->None


llist.append(6)

# Insert 7 at the beginning.


# So linked list becomes 7->6->None
llist.push(7)

# Insert 1 at the beginning.


# So linked list becomes 1->7->6->None
llist.push(1)

# Insert 4 at the end.


# So linked list becomes 1->7->6->4->None
llist.append(4)

# Insert 8, after 7.
# So linked list becomes 1->7->8->6->4->None
llist.insertAfter(llist.head.next, 8)

llist.printList(llist.head)
OUTPUT:-
6. Reverse the linked list in pairs.
Code:-

class Node:

# Constructor to initialize
the node object
def init (self, data):
self.data = data
self.next = None

class LinkedList:

# Function to initialize
head
def init (self):
self.head = None

# Function to pairwise
swap elements of a linked
list
def pairwiseSwap(self):
temp = self.head

# There are no nodes in


linked list
if temp is None:
return

# Traverse furthethr
only if there are at least two
# left
while(temp and
temp.next):

# If both nodes are


same,
# no need to swap
data
if(temp.data !=

temp.next.data):

# Swap data of
node with its next node's
data
temp.data,
temp.next.data =
temp.next.data, temp.data

# Move temp by 2 to
the next pair
temp =
temp.next.next

# Function to insert a new


node at the beginning
def push(self, new_data):
new_node =
Node(new_data)
new_node.next =
self.head
self.head = new_node

# Utility function to print


the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print temp.data,
temp = temp.next

# Driver program
llist = LinkedList()
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)

print "Linked list before


calling pairWiseSwap() "
llist.printList()

llist.pairwiseSwap()

print "\nLinked list after


calling pairWiseSwap()"
llist.printList()
OUTPUT:-
7. Write a program to construct a tree andcheck whether it is
height balanced tree.

Code:-

int solve(Node* root, bool& ans) {


if (root == nullptr || ans == false) return 0;
int left = solve(root->left, ans);
int right = solve(root->right, ans);

int temp = max(left, right) + 1;


if (abs(left-right) >= 2) {
ans = false;
return 0;
}
return temp;
}
//Function to check whether a binary tree is balanced or not.
bool isBalanced(Node *root)
{
// Your Code here
bool ans = true;
solve(root, ans);
return ans;
}OUTPUT:-

8. Construct a full binary tree using its preordertraversal and preorder


traversal of its mirror tree.

Code:-

class newNode:
def _init_(self,data):
self.data = data
self.left = self.right =
Nonedef prInorder(node):
if (node == None)
:return
prInorder(node.left)
print(node.data, end = "
")prInorder(node.right)
def constructBinaryTreeUtil(pre, preM, preIndex,l, h,
size):if (preIndex >= size or l > h) :
return None , preIndex
root =
newNode(pre[preIndex])
preIndex += 1
if (l == h):
return root, preIndex
i=0
for i in range(l, h + 1):
if (pre[preIndex] == preM[i]):
break
if (i <= h):
root.left, preIndex = constructBinaryTreeUtil(pre, preM, preIndex,i, h, size)
root.right, preIndex = constructBinaryTreeUtil(pre, preM, preIndex, l + 1, i -
size 1,
)

return root, preIndex


def constructBinaryTree(root, pre, preMirror, size):

preIndex = 0
preMIndex = 0

root, x = constructBinaryTreeUtil(pre, preMirror, preIndex,0, size - 1, size)

prInorder(root)
if _name_ =="_main_":
preOrder = [1, 2, 4, 5, 3, 6, 7]
preOrderMirror = [1, 3, 7, 6, 2, 5, 4]
size = 7
root = newNode(0)
constructBinaryTree(root, preOrder,preOrderMirror, size)

OUTPUT:-
9. Maximum length subsequence such that adjacent elements in the
subsequence have a common factor. Given an array arr[], the task
is to find the maximum length of a subsequence such that the
adjacentelements in the subsequence have a common factor.

Examples: Input: arr[] = { 13, 2, 8, 6, 3, 1, 9 }

Output: 5

Max length subsequence with satisfied conditions: { 2, 8, 6, 3, 9 }

Input: arr[] = { 12, 2, 8, 6, 3, 1, 9 }

Output: 6

Max length subsequence with satisfied conditions: {12, 2, 8, 6, 3, 9 }

Input: arr[] = { 1, 2, 2, 3, 3, 1 }

Output: 2

Code:-

import math as mt
N = 100005
MAX = 1000002
lpd = [0 for i in range(MAX)]
def preCompute():

lpd[0], lpd[1] = 1, 1

for i in range(2,
mt.ceil(mt.sqrt(MAX))):for j in
range(2 * i, MAX, i):
if (lpd[j] == 0):
lpd[j] = i

for i in range(2,
MAX):if (lpd[i] ==
0):
lpd[i] = i
def maxLengthSubsequence(arr,
n):dp = [1 for i in range(N +
1)] pos = dict()
for i in range(0, n):
while (arr[i] > 1):
p = lpd[arr[i]]
if (p in pos.keys()):
dp[i] = max(dp[i], 1 +
dp[pos[p]])pos[p] = i
while (arr[i] % p == 0):
arr[i] //= p
ans = 1
for i in range(0, n + 1):
ans = max(ans,
dp[i])
return ans
arr = [13, 2, 8, 6, 3, 1, 9]
n = len(arr)
preCompute()
print(maxLengthSubsequence(arr, n))

OUTPUT:-
10.(i)Display details of jobs where theminimum salary is
greater than 10000.

Ans:-

SELECT * FROM JOBS WHERE MIN_SALARY > 10000

(ii) Display the first name and join dateof the employees who joined
between 2002 and 2005.

Ans:-

SELECT FIRST_NAME, HIRE_DATE FROM EMPLOYEESWHERE TO_CHAR(HIRE_DATE,

'YYYY') BETWEEN 2002 AND 2005 ORDER BYHIRE_DATE.

(iii)Display first name and join date of the employees who is either IT
Programmer or Sales Man.

Ans:-
SELECTFIRST_NAME,HIRE_DATEFROM EMPLOYEES WHERE JOB_ID IN ('IT_PR',

'SA_MAN')

(iv) Display employees who joined after1st January 2008.

Ans:-

SELECT*FROMEMPLOYEES where hire_date >01-Jan-2008.

(v) Display details of employee with ID150 or 160.

Ans:-

SELECT * FROM EMPLOYEES WHERE EMPLOYEE_ID in(150,160.)

(vi).Display first name, salary, commission pct, and hire date for
employees with salary less than 10000.

Ans:-
SELECT FIRST_NAME, SALARY, COMMISSION_PCT, HIRE_DATE FROM

EMPLOYEESWHERE SALARY<10000

(vii) Display job Title, the difference between minimumand maximum salaries

for jobs with max salary in therange 10000 to 20000.

Ans:-

SELECT JOB_TITLE, MAX_SALARYMIN_SALARY DIFFERENCE FROM JOBS

WHEREMAX_SALARY BETWEEN 10000 AND 20000.

(viii) Display first name, salary, andround the salary to


thousands.

Ans:-

SELECT FIRST_NAME, SALARY, ROUND(SALARY, -3) FROM EMPLOYEES.


(ix) Display details of jobs in the
descending order of the title.

Ans:-

SELECT * FROM JOBS ORDER BY JOB_TITLE.

(x) Display employees where the firstname or last name starts with
S.

Ans:-

Select ENAME from EMP where ENAME LIKE ('S%').

(x1)Display employees who joined inthe month of May. Ans:-

SELECT *FROM employeesWHERE to_char(hire_date, 'mon')='May';


(xii)Display details of the employees where commission percentage is
null and salary in the range 5000 to 10000 and department is 30.

Ans:-

SELECT*FROMEMPLOYEESWHERECOMMISSION_PCT IS NULL AND


SALARY

BETWEEN 5000 AND 10000 AND DEPARTMENT_ID=30.

(xiii).Display first name and date of firstsalary of the employees.

Ans:-

SELECTFIRST_NAME,HIRE_DATE,LAST_DAY(HIRE_DATE)+1 FROM EMPLOYEES.

(xiv) Display first name and experienceof the employees.

Ans:-
SELECTFIRST_NAME,HIRE_DATE,FLOOR((SYSDATE-HIRE_DATE)/365)FROM

EMPLOYEES.

(xv) Display first name of employeeswho


joined in 2001.

Ans:-

SELECT FIRST_NAME, HIRE_DATE FROM EMPLOYEES WHERE TO_CHAR(HIRE_DATE,

'YYYY')=2001.

(xvi) Display first name and last name after converting the first letter of each

name to upper case and the rest to lower case.

Ans:-

SELECTINITCAP(FIRST_NAME), INITCAP(LAST_NAME) FROM EMPLOYEES.


(xvii) Display the first word in job title.

Ans:-SELECT JOB_TITLE, SUBSTR(JOB_TITLE,1, INSTR(JOB_TITLE, ' ')-

1) FROM JOBS.

(xviii) Display the length of first name foremployees where last name
contain character ‘b’ after 3rd position.

Ans:-

SELECT FIRST_NAME, LAST_NAME FROM EMPLOYEES WHERE

INSTR(LAST_NAME,'B') > 3.

(xix).Display first name in upper case and email address in lower case for
employees where the first name and email address are same irrespective of the
case.

Ans:-

SELECT UPPER(FIRST_NAME), LOWER(EMAIL) FROM EMPLOYEES WHERE

UPPER(FIRST_NAME)= UPPER(EMAIL).

(xx).Display employees who joined inthe current year.

Ans:-

SELECT*FROMEMPLOYEESWHERETO_CHAR(HIRE_DATE,'YYYY')=TO_CHAR(SYSDA

TE, 'YYYY').

(xxi).Display the number of days between system date and 1st January 2011.

Ans:-

SELECT SYSDATE - to_date('01-jan-2011') FROM DUAL.

(xxii).Display manager ID and number of employees managed by the


manager.

Ans:-

SELECT MANAGER_ID, COUNT(*) FROM EMPLOYEES GROUP BY MANAGER_ID.

(xxiii).Display employee ID and the dateon which he ended his previous job.

Ans:-

SELECT EMPLOYEE_ID, MAX(END_DATE) FROM JOB_HISTORY GROUP BY

EMPLOYEE_ID.

(xxiv) Display number of employeesjoined


after 15th of the month.

Ans:-

SELECT COUNT(*) FROM EMPLOYEES WHERE TO_CHAR(HIRE_DATE,'DD') > 15.

(xxv) Display the country ID and numberof cities we have in the


country.

Ans:-
SELECT COUNTRY_ID, COUNT(*) FROM LOCATIONS GROUP BY COUNTRY_ID.

(xxvi) Display average salary ofemployees in each department who


have commission percentage.

Ans:-

SELECT DEPARTMENT_ID, AVG(SALARY) FROM EMPLOYEES WHERE

COMMISSION_PCT IS NOT NULL GROUP BY DEPARTMENT_ID.

(xxvii) Display job ID, number of employees, sum of salary, and


difference between highest salary and lowest salary of the employees of the
job.
Ans:-

SELECT DEPARTMENT_ID, AVG(SALARY) FROM EMPLOYEES WHERE

COMMISSION_PCT IS NOT NULL GROUP BY DEPARTMENT_ID.

(xxviii) Display job ID for jobs with


average salary more than 10000.

Ans:-

SELECT JOB_ID, AVG(SALARY) FROM EMPLOYEES GROUP BY JOB_ID HAVING

AVG(SALARY)>10000.

(xxix) Display years in which more than10 employees joined.

Ans:-

SELECTTO_CHAR(HIRE_DATE,'YYYY')FROM EMPLOYEES GROUPBY

TO_CHAR(HIRE_DATE,'YYYY') HAVING COUNT(EMPLOYEE_ID) > 10

(xxx) Display departments in whichmore than five employees have


commission percentage.

Ans:-SELECT DEPARTMENT_ID FROM EMPLOYEES WHERE COMMISSION_PCT IS


NOT

NULLGROUP BY DEPARTMENT_IDHAVINGCOUNT(COMMISSION_PCT)>5.

(xxxi) Display employee ID for employees who did more than one job
in the past.

Ans:-

SELECT EMPLOYEE_ID FROM JOB_HISTORY GROUP BY EMPLOYEE_ID HAVING

COUNT(*) > 1.

(xxxii) Display job ID of jobs that were done by more than 3 employees
for more than 100 days.

Ans:-

SELECT JOB_ID FROM JOB_HISTORY WHERE END_DATE-START_DATE >


100GROUP BY JOB_ID HAVING COUNT(*)>

3.Display department ID, year, andNumber of employees joined.

Ans:-

SELECTDEPARTMENT_ID,TO_CHAR(HIRE_DATE,'YYYY'),
COUNT(EMPLOYEE_I
D) FROM EMPLOYEES GROUP BY DEPARTMENT_ID, TO_CHAR(HIRE_DATE,
'YYYY') ORDER BY DEPARTMENT_ID.

(xxxiii) Display departments where anymanager is managing more


than 5 employees.

Ans:-

SELECT DISTINCT DEPARTMENT_ID


FROM EMPLOYEES
GROUP BY DEPARTMENT_ID,
MANAGER_IDHAVING
COUNT(EMPLOYEE_ID) > 5

(xxxv).Change salary of employee 115 to 8000 if the existing salary is less


than6000.

Ans:-

UPDATE EMPLOYEES SET SALARY = 8000 WHERE EMPLOYEE_ID = 115 AND


SALARY < 6000.
(xxxvi).Change job ID of employee 110 to IT_PROG if the employee belongs
todepartment 10 and the existing job IDdoes not start with IT.

Ans:-

UPDATE EMPLOYEES SET JOB_ID= 'IT_PROG'


WHERE EMPLOYEE_ID=110 AND DEPARTMENT_ID=10 AND NOT JOB_ID LIKE 'IT%'

(xxxvii).Insert a new employee into


employees with all the required details.

Ans:-

INSERT INTO EMPLOYEES (EMPLOYEE_ID, FIRST_NAME, LAST_NAME,


EMAIL,PHONE_NUMBER, HIRE_DATE,JOB_ID, SALARY, DEPARTMENT_ID)
VALUES (207, 'ANGELA', 'SNYDER','ANGELA','215 253 4737', SYSDATE, 'SA_MAN',
12000, 80)
(xxxviii).Display department name and number of employees in the
department.
Ans:-

SELECT DEPARTMENT_NAME, COUNT(*) FROM EMPLOYEES NATURAL JOIN

DEPARTMENTS GROUP BY DEPARTMENT_NAME.

(xxxix) Display job title, employee ID, number of days between


ending date and starting date for all jobs in department 30 from job history.

Ans:-

SELECT EMPLOYEE_ID, JOB_TITLE, END_DATE-START_DATE DAYS


FROM JOB_HISTORY NATURAL JOIN JOBS
WHERE DEPARTMENT_ID=30.

(xl) Display department name,


manager name, and city.

Ans:-

SELECT DEPARTMENT_NAME, FIRST_NAME, CITY FROM DEPARTMENTS D JOIN


EMPLOYEES E ON (D.MANAGER_ID=E.EMPLOYEE_ID) JOIN LOCATIONS L USING
(LOCATION_ID).

(xxxvi) Display job title, department name, employee last name,


starting date for all jobs from 2000 to 2005.

Ans:-

SELECT JOB_TITLE, DEPARTMENT_NAME, LAST_NAME, START_DATE


FROM JOB_HISTORY JOIN JOBS USING (JOB_ID) JOIN
DEPARTMENTSUSING (DEPARTMENT_ID) JOIN EMPLOYEES USING
(EMPLOYEE_ID) WHERE TO_CHAR(START_DATE,'YYYY') BETWEEN
2000 AND 2005.

(xxxvii) Display department name, manager name, and salary of the


manager for all managers whoseexperience is more than 5 years.

Ans:-
SELECT DEPARTMENT_NAME, FIRST_NAME, SALARY
FROM DEPARTMENTS D JOIN EMPLOYEES E ON
(D.MANAGER_ID=E.MANAGER_ID) WHERE (SYSDATE-HIRE_DATE) / 365 > 5.

(xxxviii).Display employee name if theemployee joined before his


manager.

Ans:-

SELECT FIRST_NAME FROM EMPLOYEES E1 JOIN EMPLOYEES E2 ON


(E1.MANAGER_ID=E2.EMPLOYEE_ID) WHERE E1.HIRE_DATE < E2.HIRE_DATE.

(xxxix).Display employee name, job title for the jobs employee did in the past where the job
was done less than six months.

Ans:-

SELECT FIRST_NAME, JOB_TITLE FROM EMPLOYEES E JOIN JOB_HISTORY JH


ON(JH.EMPLOYEE_ID = E.EMPLOYEE_ID) JOIN JOBS J ON( JH.JOB_ID =
J.JOB_ID) WHERE
MONTHS_BETWEEN(END_DATE,START_DATE) < 6.

(xxxx).Display third highest salary of allemployees.

Ans:-

select salary
from employees main
where 2 = (select count( distinct salary
)from employees
where salary > main.salary).

(xli) Display the city of employeewhose


employee ID is 105.

Ans:-

SELECT CITY FROM LOCATIONS WHERE LOCATION_ID =


(SELECT LOCATION_ID FROM DEPARTMENTS WHERE DEPARTMENT_ID =
(SELECT DEPARTMENT_ID FROM EMPLOYEES
WHERE
EMPLOYEE_ID=105))

(xlii) Display the details of employees drawing the highest salary in


the department.
Ans:-

SELECT DEPARTMENT_ID,FIRST_NAME, SALARY FROM EMPLOYEES


OUTERWHERE SALARY =
SELECT MAX(SALARY) FROM EMPLOYEES WHERE DEPARTMENT_ID =
OUTER.DEPARTMENT_ID)

(xliii) Display details of current job foremployees who worked as IT


Programmers in the past.

Ans:-

SELECT * FROM JOBS


WHERE JOB_ID IN
(SELECT JOB_ID FROM EMPLOYEES WHERE EMPLOYEE_ID IN
(SELECT EMPLOYEE_ID FROM JOB_HISTORY WHERE JOB_ID='IT_PROG'))

(xliv) Display the details ofdepartments in which the max salary


is greater than 10000 for employees who did a job in the past.

Ans:-

SELECT * FROM DEPARTMENTS


WHERE DEPARTMENT_ID IN
(SELECT DEPARTMENT_ID FROM EMPLOYEES
WHERE EMPLOYEE_ID IN (SELECT EMPLOYEE_ID FROM JOB_HISTORY)
GROUP BY DEPARTMENT_ID
HAVING MAX(SALARY) >10000).

(xlv) Display the departments intowhich no employee joined in


last two years.

Ans:-

SELECT * FROM DEPARTMENTSWHERE DEPARTMENT_ID NOT IN


(SELECT DEPARTMENT_ID FROM EMPLOYEES WHERE
FLOOR((SYSDATE-HIRE_DATE)/365) < 2).

(xlvi) Display employee name, job title,start date, and end date of past
jobs ofall employees with commissionpercentage
null.

Ans:-

SELECT FIRST_NAME, JOB_TITLE, START_DATE, END_DATE


FROM JOB_HISTORY JH JOIN JOBS J USING (JOB_ID) JOIN EMPLOYEES E
ON
( JH.EMPLOYEE_ID = E.EMPLOYEE_ID)
WHERE COMMISSION_PCT IS NULL.

(xxxxvii).Display details of managerwho


manages more than 5 employees.

Ans:-

SELECT FIRST_NAME FROM EMPLOYEES


WHERE EMPLOYEE_ID IN
(SELECT MANAGER_ID FROM EMPLOYEES
GROUP BY MANAGER_ID
HAVING COUNT(*)>5).

(xlviii) Display country name, city, and number of departments


where department has more than 5 employees.

Ans:-

SELECT COUNTRY_NAME, CITY, COUNT(DEPARTMENT_ID)


FROM COUNTRIES JOIN LOCATIONS USING (COUNTRY_ID) JOIN
DEPARTMENTSUSING (LOCATION_ID)
WHERE DEPARTMENT_ID IN
(SELECT DEPARTMENT_ID FROM EMPLOYEES
GROUP BY DEPARTMENT_ID
HAVING
COUNT(DEPARTMENT_ID)>5)GROUP BY
COUNTRY_NAME, CITY;

(xlix) Display job title and average salary for employees who did
a job in the past.

Ans:-

SELECT JOB_TITLE, AVG(SALARY) FROM JOBS NATURAL JOIN


EMPLOYEESGROUP BY JOB_TITLE
WHERE EMPLOYEE_ID IN
(SELECT EMPLOYEE_ID FROM JOB_HISTORY).

(l) Display employees who did notdo any job in the past.

Ans:-

SELECT * FROM EMPLOYEES WHERE EMPLOYEE_ID NOT


IN(SELECT EMPLOYEE_ID FROM JOB_HISTORY).

(li) Display the month in which more than 5 employees joined


in any department located in Sydney.

Ans:-

SELECT TO_CHAR(HIRE_DATE,'MON-YY')
FROM EMPLOYEES JOIN DEPARTMENTS USING (DEPARTMENT_ID)
JOINLOCATIONS USING (LOCATION_ID)
WHERE CITY = 'Seattle'
GROUP BY TO_CHAR(HIRE_DATE,'MON-YY')
HAVING COUNT(*) > 5.

(xxxxxii).Display details of departments in which the maximum salary is more


than 10000.

Ans:-

SELECT * FROM DEPARTMENTS WHERE DEPARTMENT_ID IN


( SELECT DEPARTMENT_ID FROM
EMPLOYEESGROUP BY DEPARTMENT_ID
HAVING MAX(SALARY)>10000)

(liii) Display details of departmentsmanaged by ‘Smith’.

Ans:-

SELECT * FROM DEPARTMENTS WHERE MANAGER_ID IN


(SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE FIRST_NAME='SMITH')

(liv) Display jobs into which


employees joined in the current year.

Ans:-

SELECT * FROM JOBS WHERE JOB_ID IN


(SELECT JOB_ID FROM EMPLOYEES
WHERE
TO_CHAR(HIRE_DATE,'YYYY')=TO_CHAR(SYSDATE,'YYYY')).
11.m Coloring ProblemGiven an undirected graph and a number m, determine if
the graph can be coloured with at most m colours such that no two
a djacentvertices of the graph are colored with the same color. Here coloring
of a graph means the assignment of colors to all vertices. Input-Output
format: Input: A 2D array graph[V][V] where V is the number of vertices
in graph and graph[V][V] is an adjacency matrix representation of the graph.
A value graph[i][j] is 1 if there is a direct edge from i to j, otherwise
graph[i][j] is 0.An integer m is the maximum number of colors that can be
used.Output: An array color[V] that should have numbers from 1 to m.
color[i] should represent the color assigned to the ith vertex.

The code should also return false if the graph cannot be colored with m

colors.Input: graph = {0, 1, 1, 1}{1, 0, 1, 0},{1, 1, 0, 1},{1, 0, 1, 0}Output: Solution


Exists: Following are the assigned colors1 2 3 2

12.Explanation: By coloring the vertices with following colors, adjacent

vertices does not have same colors


Input: graph = {1, 1, 1, 1},

{1, 1, 1, 1},

{1, 1, 1, 1},

{1, 1, 1, 1}

Output: Solution does not exist.

Explanation: No solution exits.


Ans:-
#include<bits/stdc++.h>
using namespace std;

// Number of vertices in the graph


#define V 4

void printSolution(int color[]);

// check if the colored


// graph is safe or not
bool isSafe(bool graph[V][V], int color[])
{
// check for every edge
for (int i = 0; i < V; i++)
for (int j = i + 1; j < V; j++)
if (graph[i][j] && color[j] == color[i])
return false;
return true;
}

/* This function solves the m Coloring


problem using recursion. It returns
false if the m colours cannot be assigned,
otherwise, return true and prints
assignments of colours to all vertices.
Please note that there may be more than
one solutions, this function prints one
of the feasible solutions.*/
bool graphColoring(bool graph[V][V], int m, int i,
int color[V])
{
// if current index reached end
if (i == V) {

// if coloring is safe
if (isSafe(graph, color)) {

// Print the solution


printSolution(color);
return true;
}
return false;
}

// Assign each color from 1 to m


for (int j = 1; j <= m; j++) {
color[i] = j;

// Recur of the rest vertices


if (graphColoring(graph, m, i + 1, color))
return true;

color[i] = 0;
}

return false;
}
/* A utility function to print solution */
void printSolution(int color[])
{
cout << "Solution Exists:" " Following are the assigned colors \n";
for (int i = 0; i < V; i++)
cout << " " << color[i];
cout << "\n";
}

// Driver code
int main()
{
/* Create following graph and
test whether it is 3 colorable
(3)---(2)
|/|
|/|
|/|
(0)---(1)
*/
bool graph[V][V] = {
{ 0, 1, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 1 },
{ 1, 0, 1, 0 },
};
int m = 3; // Number of colors

// Initialize all color values as 0.


// This initialization is needed
// correct functioning of isSafe()
int color[V];
for (int i = 0; i < V; i++)
color[i] = 0;

if (!graphColoring(graph, m, 0, color))
cout << "Solution does not exist";

return 0;
}
OUTPUT:-

2.PL/SQL COMMANDS.

(a)

Create a program that accepts two numbers from substitution variables, display
one of the following messages:-

first is greater than secondfirst is less

than second first is the same as

second.

Ans:-

DECLARE
l_number1 NUMBER := &1;
l_number2 NUMBER := &2;
BEGIN
IF l_number1 > l_number2 THEN
DBMS_OUTPUT.put_line('first is greater than
second'); ELSIF l_number1 < l_number2 THEN
DBMS_OUTPUT.put_line('first is less than second');
ELSE
DBMS_OUTPUT.put_line('first is same as
second'); END IF;
END;
(b)

Create a program that accepts a single number. Display the message Hello
World X times, where X is the number entered.

Ans:-

DECLARE
l_times NUMBER := &1;
BEGIN
FOR l_loop IN
1..l_timesLOOP
DBMS_OUTPUT.put_line('Hello World');
END LOOP;
END;

(c)

Try running the above program and entering a negative number, what happens?
Change the code to print a message if a number less than 1 is entered that informs
the user they must enter a number greater than or equal to 1.

Ans:-

DECLARE
l_times NUMBER := &1;
BEGIN
IF l_times < 1 THEN
DBMS_OUTPUT.put_line('Number must be at least
1'); ELSE
FOR l_loop IN
1..l_timesLOOP
DBMS_OUTPUT.put_line('Hello World');
END LOOP;
END
IF;
END;

SQL WITHIN PL/SQL

(a)

Write a program that gives all employees in department 10 a 15% pay increase.
Display a messagedisplaying how many employees were awarded the increase.

Ans:-

BEGIN
UPDATE emp
SET sal = sal * 1.15
WHERE deptno =
10;
DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||
' employee(s)
updated'); END;

(B)Create a PL/SQL block that accepts a new job title and an old job title. Find all
employees in the old job and give them the new job. Ensure a valid message is given
back to the user even if no employees changed job.

Ans:-

DECLARE
l_old_job emp.job%TYPE :=
'&1'; l_new_job emp.job%TYPE
:= '&2'; BEGIN
UPDATE emp
SET job = l_new_job
WHERE job =
l_old_job;IF
SQL%FOUND THEN
DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||
' employee(s) changed
job'); ELSE
DBMS_OUTPUT.put_line('No employee found with
job'|| ' of '||l_old_job);
END
IF;
END;
EXPLICIT CURSORS

(a)

Create a program that mimics selecting all columns and rows from the dept table.
There is no need to format the output, just select all columns and all rows.Use a
cursor FOR loop.

Ans:-

DECLARE
CURSOR
dept_curIS
SELECT deptno
, dname
, loc
FROM
dept;
BEGIN
FOR r_dept in
dept_curLOOP
DBMS_OUTPUT.put_line(r_dept.deptno
);
DBMS_OUTPUT.put_line(r_dept.dname
);DBMS_OUTPUT.put_line(r_dept.loc);
END LOOP;
END;
(b)

Create a program that copies all departments to a table called old_dept. Do not
use a cursor FOR loop. Display how many rows were copied.

Ans:-

DECLARE
CURSOR
dept_curIS
SELECT deptno
, dname
, loc
FROM dept;
r_dept
dept_cur%ROWTYPE;
BEGIN
OPEN dept_cur;
LOOP
FETCH dept_cur INTO r_dept;
EXIT WHEN dept_cur%NOTFOUND;
INSERT INTO old_dept
(deptno,dname,loc) VALUES
(r_dept.deptno,r_dept.dname,r_dept.lo
c);END LOOP;
DBMS_OUTPUT.put_line(TO_CHAR(dept_cur%ROWCOUN
T)|| ' department(s) copied');
CLOSE
dept_cur;END;
PROCEDURES/FUNCTIONS

(a) Create a procedure that deletes rows from the old_emp table. It should accept 1
parameter, job; only delete the employee’s with that job. Display how many
employees were deleted. Write a program to invoke the procedure.

Ans:-

CREATE OR REPLACE PROCEDURE DelEmp(p_job IN


emp.job%TYPE) IS
BEGIN
DELETE old_emp
WHERE job = p_job;
DBMS_OUTPUT.put_line(TO_CHAR(SQL%ROWCOUNT)||' removed');
END;
To invoke the
procedure:-BEGIN
DelEmp('CLERK')
; END;

(B)Change the above procedure so that it returns the number of employees removed via
an OUT parameter. Write a program to invoke the procedure and displayhow many
employees were deleted.

Ans:-

CREATE OR REPLACE PROCEDURE DelEmp( p_job IN emp.job%TYPE


, p_count OUT
NUMBER)IS
BEGIN
DELETE old_emp
WHERE job = p_job;
p_count :=
SQL%ROWCOUNT; END;
To invoke the
procedure:-DECLARE
l_count
NUMBER;BEGIN
DelEmp('CLERK',l_count);
DBMS_OUTPUT.put_line(l_count);
END;

(c) Convert the above program to a function. Instead of using an OUT parameter for the
number of employeesdeleted, use the functions return value. Write a program to
invoke the function and display how many employees were deleted.
Ans:-

CREATE OR REPLACE FUNCTION DelEmp(p_job IN emp.job%TYPE)


RETURN NUMBER
IS
BEGIN
DELETE old_emp
WHERE job = p_job;
RETURN
SQL%ROWCOUNT; END;
To invoke the function:-
DECLARE
l_count
NUMBER;BEGIN
l_count := DelEmp('CLERK');
DBMS_OUTPUT.put_line(l_count);
END;

You might also like