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

VIIT, Pune

Lab Manual

Data Structures and Algorithm


Lab
for
2020PATTERN

Issue No: 01 Issue


Date: Copy No: 01
Copy Holder: Practical

Name: Swarup Suresh Devde


Roll no. 251012
Prn no. 22110558
Batch : A1
DSA Lab Manual SE MECH, Sem-I, 2022-23

BANSILAL RAMNATH AGARWAL CHARITABLE

TRUST’S

Vishwakarma Institute of Information Technology


Survey No. 3/4, Kondhwa (Budruk)
Pune – 411048, Maharashtra (India)

Department of Mechanical Engineering

Lab Manual for

SE COMPUTER

Semester I Academic Year 2022-23

Data Structure and Algorithms Lab

MEUA21207

Teaching Scheme Examination Scheme:


Practical: 2 Hrs. /Week Practical/Oral Assessment: 50 Marks

Practical In charge,
Mrs. Pradnya S. Mehta
Dr. Dattatray G. Takale

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Programme Outcomes:

Students are expected to know and be able –

1. To apply knowledge of mathematics, science, engineering fundamentals, problem solving skills,


algorithmic analysis and mathematical modelling to the solution of complex engineering problems.

2. To analyse the problem by finding its domain and applying domain specific skills

3. To understand the design issues of the product/software and develop effective solutions with
appropriate consideration for public health and safety, cultural, societal, and environmental
considerations.

4. To find solutions of complex problems by conducting investigations applying suitable techniques.

5. To adapt the usage of modern tools and recent software.

6. To contribute towards society by understanding the impact of Engineering on global aspect.

7. To understand environment issues and design a sustainable system.

8. To understand and follow professional ethics.

9. To function effectively as an individual and as member or leader in diverse teams and


interdisciplinary settings.

10. To demonstrate effective communication at various levels.

11. To apply the knowledge of Computer Engineering for development of projects, and its finance
and management.

12. To keep in touch with current technologies and inculcate the practice of lifelong learning.

Course Objectives:
1) To study data structures and their implementations and applications.
2) To learn different searching and sorting techniques.
3) To study some advanced data structures such as trees, graphs and tables.
4) To learn algorithm development and analysis of algorithms.
Course Outcomes:
On completion of the course, learners will be able to
1. Perform basic analysis of algorithms with respect to time and space complexity.
2. Select appropriate searching and/or sorting techniques and Implement data structures for
given application.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

INDEX
Assignment. Title of Assignment Page
No. No.

1 Represent matrix using two dimensional arrays and perform following 10


operations
i. Addition
ii. multiplication
iii. Transpose
2 Write a menu driven Program in C++ for the following operations on Singly 13
Linked List (SLL) of Student Data with the fields: PRN, Name, Branch,
Semester, Cell Number
a. Create a SLL of N Students
b. Display the SLL and count the number of nodes in it
c. Perform Insertion
d. Perform Deletion
3 3. Perform implementation of STACK using Array 17
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate Overflow and Underflow situations on Stack
d. Display Stack Support the program with appropriate functions for each of
the above operations

4 Implement FCFS (Queue) algorithm of job scheduling in operating system 19


with the help of suitable data structure.

5 Write C++ program to maintain club members, sort on roll numbers in 23


ascending order. Write function for Binary Search and Linear Search to search
whether particular student is member of club or not.

6 Department maintains student’s database. The file contains roll number,name, 25


division and address. Write a program to create a sequential file to store and
maintain student data. It should allow the user to add, deleteinformation of
student. Display information of particular student. If record ofstudent does not
exist an appropriate message is displayed. If student recordis found it should
display the student details.

7 Represent graph as adjacency matrix or list and perform Depth first Traversal 28
and Breadth First Traversal

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

CO-PO-PSO Mapping
CO-PO Mapping

PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO

Perform 3 3 3 3
basic
analysis of
algorithms
with
respect to
time and
space
complexity.

Select 3 3 3 3
appropriate
searching
and/or
sorting
techniques
and
Implement
data
structures
for given
application.

CO-PSO Mapping

PO PSO1 PSO2
CO

Perform basic analysis of algorithms with respect to time and space 2


complexity.

Select appropriate searching and/or sorting techniques and Implement 2


data structures for given application.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT 1

TITLE: Matrix operations

AIM/ Problem Statement: Write a program to perform operations on matrices like addition,
multiplication, transpose etc using functions & Pointers.

Prerequisites: Student should know matrix concepts.

Relevant Course Objectives: Learn how to use matrix

Theory:

A matrix (plural matrices) is a rectangular array of numbers, symbols, or expressions, arranged in


rows and columns the individual items in a matrix are called its elements or entries. An example of a
matrix with 2 rows and 3 columns is

Basic operations

Operation Definition Example

The sum A+B of two m-


by-n matrices A and B is
calculated entry wise:
Addition (A + B)i,j = Ai,j+ B
i,j, where 1
≤ i ≤ m and 1
≤ j ≤ n.
The scalar multiplication
c A of a matrix A and a
number c (also called
Scalar a scalar in the parlance of
multiplicatio abstract algebra) is given
n by multiplying every
entry of A by c:
(cA)i,j = c · Ai,j.

The transpose of an m-by-


n matrixA is the n-by-
Transpose mmatrix AT (also
denoted Atr or tA) formed
by turning rows into

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

columns and vice versa:


(AT)i,j = Aj,i.

Algorithmic Steps/Pseudo code/Program:

Addition of 2 matrices algorithm

• Input Two matrices a and b


• Output Output matrix c containing elements after addition of a and b
• complexity O(n^2)
• Matrix-Addition(a,b)
• for i =1 to rows [a]
• for j =1 to columns[a]
• Input a[i,j];
• Input b[i,j];
• C[i, j] = A[i, j] + B[i, j];
• Display C[i,j];

Subtraction of 2 matrices algorithm

• Input Two matrices a and b


• Output Output matrix c containing elements after addition of a and b
• complexity O(n^2)

• Matrix-subtraction(a,b)
• for i =1 to rows [a]
• for j =1 to columns[a]
• Input a[i,j];
• Input b[i,j];
• C[i, j] = A[i, j] - B[i, j];

Display C[i,j];

Multiplication of 2 matrices

1. Input two matrixes.


2. Output Output matrix C.
3. Complexity O(n^3)
4.
5. Matrix-Multiply(A, B)
6. 1 if columns [A] ≠ rows [B]
7. 2 then error "incompatible dimensions"
8. 3 else
9. 4 for i =1 to rows [A]
10. 5 for j = 1 to columns [B]

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

11. 6 C[i, j] =0
12. 7 for k = 1 to columns [A]
13. 8 C[i, j]=C[i, j]+A[i, k]*B[k, j]
14. 9 return C

Transpose of 2 matrices

1. transpose(A, B);
2. cout << "Result matrix is \n";
3. for (i = 0; i < N; i++) {
4. for (j = 0; j < N; j++)
5. cout << " " << B[i][j];
6. cout << "\n";
7. }
Return

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
Source Code:
#include <iostream>

using namespace std;


void createm1(int a[10][10],int r1,int c1);
void display( int sum[10][10],int r1,int c1);
int main()
{
int a[10][10], b[10][10], c[10][10], r1, c1, r2, c2, i, j, ch,sum[10][10],mul[10][10],k;
char ch1;
cout << "Enter rows and columns matrix: ";
cin >> r1 >> c1;
cout << endl << "Enter elements of 1st matrix: " << endl;

do
{
cout <<" ***menu***";
// cout << "1) Transpose of the Matrix" <<endl;
cout<< "1)Add two matrices" <<endl;
cout<<" 2)Multiply two matrices"<<endl;
cout<<"3) Tanspose of matrix"<<endl;
cout<<"\nEnter Your Choice : ";
cin>>ch;

switch(ch)
{
case 1:

// Storing elements of first matrix entered by user.


cout << "Enter rows and columns for first matrix: ";
createm1(a,r1,c1);
display(a,r1,c1);
cout << "Enter rows and columns for second matrix: ";
createm1(b,r1,c1);
display(b,r1,c1);

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


for(j = 0; j < c1; ++j)
sum[i][j] = a[i][j] + b[i][j];
cout << endl << "Sum of two matrix is: " << endl;
display(sum,r1,c1);
break;
case 2:

// Storing elements of first matrix entered by user.


cout << "Enter rows and columns for first matrix: ";
createm1(a,r1,c1);
cout << "Enter rows and columns for second matrix: ";
createm1(b,r1,c1);
cout<<"multiply of the matrix=\n";
for(i=0;i<r1;i++)
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
{
for(j=0;j<c1;j++)
{
mul[i][j]=0;
for(k=0;k<c1;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
display(mul,r1,c1);
break;

case 3:
cout << "Enter rows and columns for first matrix: ";
createm1(a,r1,c1);

cout<<"transpose of the matrix=\n";


for (int i = 0; i < r1; ++i)
for (int j = 0; j < c1; ++j) {
c[j][i] = a[i][j];
}
display(c,r1,c1);
break;

}
cout<<"\n Do u want to continue\n";
cin>>ch1;

}while(ch1=='Y' || ch1=='y');

return 0;
}

void createm1(int a[10][10],int r1,int c1)


{
int i,j;
for(i = 0; i < r1; ++i)
for(j = 0; j < c1; ++j)
{
cout << "Enter element a" << i + 1 << j + 1 << " : ";
cin >> a[i][j];
}
cout<<"matrix is created"<<endl;
}

void display(int c[10][10],int r1,int c1)

{
int i,j;
for(i = 0; i < r1; ++i)
for(j = 0; j < c1; ++j)
{
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
cout << c[i][j] << " ";
if(j == c1 - 1)
cout << endl;
}
}

Output: Soft copy of program with output.

Conclusion:
Thus we have studied various matrix operations.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT 2

TITLE: Write a menu driven Program in C++ for the following operations on Singly Linked List
(SLL) of Student Data with the fields: PRN, Name, Branch, Semester, Cell Number
a. Create a SLL of N Students
b. Display the SLL and count the number of nodes in it
c. Perform Insertion
d. Perform Deletion

Aim/ Problem Statement: Write a menu driven program to perform following operations on SLL:
Create, Insert – Start, end, between, Search & delete, Display etc.

Prerequisites: Knowledge about link list

Relevant Course Objectives: To learn the concept of link list and perform various operations on it.

Theory:

A linked list is a data structure consisting of a group of nodes which together represent a sequence.
Under the simplest form, each node is composed of a data and a reference (in other words, a link) to
the next node in the sequence; more complex variants add additional links. This structure allows for
efficient insertion or removal of elements from any position in the sequence.

The principal benefit of a linked list over a conventional array is that the list elements can easily be
inserted or removed without reallocation or reorganization of the entire structure because the data
items need not be stored contiguously in memory or on disk, while an array has to be declared in the
source code, before compiling and running the program.
Singly linked list

Singly linked lists contain nodes which have a data field as well as a next field, which points to the
next node in line of nodes. Operations that can be performed on singly linked lists include insertion,
deletion and traversal.

A singly linked list whose nodes contain two fields: an integer value and a link to the next node
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Doubly linked list

In a doubly linked list, each node contains, besides the next-node link, a second link field pointing
to the previous node in the sequence. The two links may be called forward(s) and backwards,
or next and prev(previous).

A doubly linked list whose nodes contain three fields: an integer value, the link forward to the next
node, and the link backward to the previous node

A technique known as XOR-linking allows a doubly linked list to be implemented using a single
link field in each node. However, this technique requires the ability to do bit operations on
addresses, and therefore may not be available in some high-level languages.

Input:

Algorithmic Steps/Pseudo code/Program:

Insertion at the head

Insert a new node at the head of the list is straightforward. The main idea is that we create a new
node, set its next link to refer to the current head, and then set head to point to the new node.

Algorithm addFirst(String newData):


create a new node v containing newData
v.setNext(head)
head = v
size = size + 1

Insertion at the tail

If we keep a reference to the tail node, then it would be easy to insert an element at the tail of the list.
Assume we keep a tail node in the class of SLinkedList, the idea is to create a new node, assign its
next reference to point to a null object, set the next reference of the tail to point to this new object,
and then assign the tail reference itself to this new node. Initially both head and tail point to null
object.

Algorithm addLast(String newData):


create a new node v containing newData

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

v.setNext(null)
if (head == null) { // list is empty
head = v
} else { // list is not empty
tail.setNext(v)
}
tail = v
size = size + 1

Deletion at the head

Removal of an element at the head of a singly linked list is relatively easy. However removing a tail
node is not easy.

Algorithm removeFirst()
if (head = = null) then
Indicate an error: the list is empty
tmp = head
head = head.getNext()
tmp.setNext(null)
size = size - 1

Traversing a Singly Linked List


Stepping through, or traversing, all the entries of a linked list from beginning to end following the
chain of references is a useful operation in practice. Moreover, this process may be enhanced to
search for and locate specific nodes.

Algorithm traverseList()
curNode = head
while (curNode != null) {
// print out the contents of the current node
curNode = curNode.getNext()
}

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
Source Code:
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int roll;
string Name;
string Dept;
int Marks;
Node* next;
};
Node* head = new Node();
bool check(int x)
{
if (head == NULL)
return false;

Node* t = new Node;


t = head;

while (t != NULL) {
if (t->roll == x)
return true;
t = t->next;
}

return false;
}

void Insert_Record(int roll, string Name,


string Dept, int Marks)
{
if (check(roll)) {
cout << "Student with this "
<< "record Already Exists\n";
return;
}

Node* t = new Node();


t->roll = roll;
t->Name = Name;
t->Dept = Dept;
t->Marks = Marks;
t->next = NULL;

if (head == NULL
|| (head->roll >= t->roll)) {
t->next = head;
head = t;
}

else {
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
Node* c = head;
while (c->next != NULL
&& c->next->roll < t->roll) {
c = c->next;
}
t->next = c->next;
c->next = t;
}

cout << "Record Inserted "


<< "Successfully\n";
}

void Search_Record(int roll)


{
if (!head) {
cout << "No such Record "
<< "Available\n";
return;
}

else {
Node* p = head;
while (p) {
if (p->roll == roll) {
cout << "Roll Number\t"
<< p->roll << endl;
cout << "Name\t\t"
<< p->Name << endl;
cout << "Department\t"
<< p->Dept << endl;
cout << "Marks\t\t"
<< p->Marks << endl;
return;
}
p = p->next;
}

if (p == NULL)
cout << "No such Record "
<< "Available\n";
}
}

int Delete_Record(int roll)


{
Node* t = head;
Node* p = NULL;

if (t != NULL
&& t->roll == roll) {
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
head = t->next;
delete t;

cout << "Record Deleted "


<< "Successfully\n";
return 0;
}

while (t != NULL && t->roll != roll) {


p = t;
t = t->next;
}
if (t == NULL) {
cout << "Record does not Exist\n";
return -1;
p->next = t->next;

delete t;
cout << "Record Deleted "
<< "Successfully\n";

return 0;
}
}

void Show_Record()
{
Node* p = head;
if (p == NULL) {
cout << "No Record "
<< "Available\n";
}
else {
cout << "Index\tName\tCourse"
<< "\tMarks\n";

while (p != NULL) {
cout << p->roll << " \t"
<< p->Name << "\t"
<< p->Dept << "\t"
<< p->Marks << endl;
p = p->next;
}
}
}

int main()
{
head = NULL;
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
string Name, Course;
int Roll, Marks;

while (true) {
cout << "\n\t\tWelcome to Student Record "
"Management System\n\n\tPress\n\t1 to "
"create a new Record\n\t2 to delete a "
"student record\n\t3 to Search a Student "
"Record\n\t4 to view all students "
"record\n\t5 to Exit\n";
cout << "\nEnter your Choice\n";
int Choice;

cin >> Choice;


if (Choice == 1) {
cout << "Enter Name of Student\n";
cin >> Name;
cout << "Enter Roll Number of Student\n";
cin >> Roll;
cout << "Enter Course of Student \n";
cin >> Course;
cout << "Enter Total Marks of Student\n";
cin >> Marks;
Insert_Record(Roll, Name, Course, Marks);
}
else if (Choice == 2) {
cout << "Enter Roll Number of Student whose "
"record is to be deleted\n";
cin >> Roll;
Delete_Record(Roll);
}
else if (Choice == 3) {
cout << "Enter Roll Number of Student whose "
"record you want to Search\n";
cin >> Roll;
Search_Record(Roll);
}
else if (Choice == 4) {
Show_Record();
}
else if (Choice == 5) {
exit(0);
}
else {
cout << "Invalid Choice "
<< "Try Again\n";
}
}
return 0;
}

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Output: Soft copy of program with output.

Conclusion:

Thus we ha

ve studied various SLL operations.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT NO: 3

Title: Perform implementation of STACK using Array


a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate Overflow and Underflow situations on Stack
d. Display Stack Support the program with appropriate functions for each of the above operations
AIM/ PROBLEM STATEMENT: Write a menu driven program to perform following operations
on Stack Using Array: Create Push, POP, and Display etc.

Prerequisites: Knowledge about stack and Array

Relevant Course Objectives: To learn the concept of Stack using Array and perform various
operations on it.

Theory:

A stack data structure can be implemented using a one-dimensional array. But stack implemented
using array stores only a fixed number of data values. This implementation is very simple. Just define
a one dimensional array of specific size and insert or delete the values into that array byusing
LIFO principle with the help of a variable called 'top'. Initially, the top is set to -1. Whenever we want
to insert a value into the stack, increment the top value by one and then insert. Whenever we want to
delete a value from the stack, then delete the top value and decrement the top value by one.

Input:

Stack Operations using Array

A stack can be implemented using array as follows. Before implementing actual operations, first
follow the below steps to create an empty stack.
Step 1: Include all the header files which are used in the program and define a constant 'SIZE' with
specific value.
Step 2: Declare all the functions used in stack implementation.
Step 3: Create a one dimensional array with fixed size (int stack[SIZE])
Step 4: Define a integer variable 'top' and initialize with '-1'. (int top = -1)
Step 5: In main method, display menu with list of operations and make suitable function calls to
perform operation selected by the user on the stack.

Push(value) - Inserting value into the stack

In a stack, push () is a function used to insert an element into the stack. In a stack, the new element
is always inserted at top position. Push function takes one integer value as parameter and inserts that
value into the stack. We can use the following steps to push an element on to the stack...
Step 1: Check whether stack is FULL. (top == SIZE-1)

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Step 2: If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and terminate the
function.
Step 3: If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).

Pop() - Delete a value from the Stack

In a stack, pop() is a function used to delete an element from the stack. In a stack, the element is
always deleted from top position. Pop function does not take any value as parameter. We can use the
following steps to pop an element from the stack...
Steps 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate
the function.
Step 3: If it is NOT EMPTY, then delete stack [top] and decrement top value by one (top--).

Display () - Displays the elements of a Stack

We can use the following steps to display the elements of a stack...


Step 1: Check whether stack is EMPTY. (top == -1)
Step 2: If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.
Step 3: If it is NOT EMPTY, then define a variable 'i' and initialize with top. Display stack[i] value
and decrement i value by one (i--).
Step 4: Repeat above step until i value becomes '0'.

Source Code:

#include <iostream>
using namespace std;
int stack[100], n=100, top=-1;
void push(int val) {
if(top>=n-1)
cout<<"Stack Overflow"<<endl;
else {
top++;
stack[top]=val;
}
}
void pop() {
if(top<=-1)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< stack[top] <<endl;
top--;
}
}
void display() {
if(top>=0) {
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
cout<<"Stack elements are:";
for(int i=top; i>=0; i--)
cout<<stack[i]<<" ";
cout<<endl;
} else
cout<<"Stack is empty";
}
int main() {
int ch, val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=4);
return 0;
}

Output: Soft copy of program with output.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Conclusion:
Thus we have studied various Stack using Array operations.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT NO: 4

Title: Implement FCFS (Queue) algorithm of job scheduling in operating system with the help of suitable
data structure.

AIM/ PROBLEM STATEMENT: Implement FCFS (Queue) algorithm of job scheduling in


operating system with the help of suitable data structure.

Prerequisites: Knowledge about Queue and Job Scheduling algorithms.

Relevant Course Objectives: To learn the concept of Queues using

Theory:

When we run a program, we create a particular instance of the program called process. There might
be a condition where more than one process is created at a given time and the CPU has to serve all
the processes. There is a various process scheduling algorithm that decides which process has to be
executed at a given time by considering various factors. FCFS or First come first serve is one such
algorithm that schedules the process

Scope

This article will explain the FCFS algorithm along with the Gantt chart.

Implementation of FCFS algorithm using CPP.

Advantages and disadvantages of the algorithm

What is First Come First Serve Scheduling?

The first come first serve scheduling algorithm is non-preemptive in nature i.e, if a process is already
running, then it is not interrupted by another process until the currently running process is executed
completely.

Buying a movie ticket from the ticket counter is a perfect real-life example of a first come first
serve (fcfs) algorithm. The person who comes first and stands in the queue gets to buy the ticket first.
Similarly in the fcfs scheduling algorithm, the process which arrives first gets executed first.

Input:

How does FCFS Scheduling Work?

Let us consider an example where 4 processes with different burst times arrive at different times.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Process Burst Time Arrival time

P1 6 2

P2 8 1

P3 3 0

P4 4 4

Let us see how the above processes are handled using the First come first serve scheduling
algorithm.

At time t=0

Process Burst Time Arrival time

P1 6 2

P2 8 1

P3 3 0 (please add this row in different color)

P4 4 4

From the above chart, we can see that at time 0, the process P3 arrives. Once the process P3 arrives,
the process is served as there is no other process that is being executed.

At time t=1

Process Burst Time Arrival time

P1 6 2

1 (please add this row in different color but same color as the one used
P2 8
in previous image)

P3 3 0

P4 4 4

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

The process P2 arrives at time t=1, but the program P3 is still executing. The process P2 will be
kept in a queue which will be executed after the existing process finishes its execution. Queue

Gantt Chart

At time t=2

Process Burst Time Arrival time

2 (please add this row in different color but same color as the one used
P1 6
in previous image)

P2 8 1

P3 3 0

P4 4 4

At time t=2, Process P1 arrives and waits in the queue as there is another process being executed.

Queue

At time t=3

At time t=3, Process P3 finished execution after 3 seconds. In the queue, the process P2 is waiting
for the execution Therefore process P2 begins its execution.

At time t=5

Process Burst Time Arrival time

P1 6 2

P2 8 1

P3 3 0

4 (please add this row in different color but same color as the one used in
P4 4
previous image)

At time t=5, Process P4 arrives and waits in the queue.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

At time t=21

In the end, at time t=21

Characteristics of FCFS Algorithm

The first come first serve is a simple scheduling algorithm

The process which arrives first would be served first based on a first come first serve basis.

This method is easy to understand and implement.

Source Code:

#include<iostream>
using namespace std;
int main()
{
int n,bt[20],wt[20],tat[20],avwt=0,avtat=0,i,j;
cout<<"Enter total number of processes(maximum 20):";
cin>>n;

cout<<"\nEnter Process Burst Time\n";


for(i=0;i<n;i++)
{
cout<<"P["<<i+1<<"]:";
cin>>bt[i];
}

wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
}

cout<<"\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time";


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
avwt+=wt[i];
avtat+=tat[i];
cout<<"\nP["<<i+1<<"]"<<"\t\t"<<bt[i]<<"\t\t"<<wt[i]<<"\t\t"<<tat[i];
}

avwt/=i;

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
avtat/=i;
cout<<"\n\nAverage Waiting Time:"<<avwt;
cout<<"\nAverage Turnaround Time:"<<avtat;

return 0;
}

Conclusion:
Thus we have studied FCFS (Queue) algorithm of job scheduling.

Output: Soft copy of program with output.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT NO: 5

Title: Write C++ program to maintain club members, sort on roll numbers in ascending order. Write
function for Binary Search and Linear Search to search whether particular student is member of club or
not.

AIM/ PROBLEM STATEMENT: Write C++ program to maintain club members, sort on roll numbers
in ascending order. Write function for Binary Search and Linear Search to search whether particular
student is member of club or not.

Prerequisites: Knowledge about Binary Search and Linear Search

Relevant Course Objectives: To learn the concept unction for Binary Search and Linear Search to
search whether particular student is member of club or not.

Theory:

A search algorithm is an algorithm for finding an item with specified properties among
a collection of items.

Sequential search: is a method for finding a particular value in a list that consists of checking
every one of its elements, one at a time and in sequence, until the desired one is found.

Binary search or half-interval search algorithm finds the position of a specified input value (the
search "key") within an array sorted by key value.
.
Indexed sequential Search: An index file can be used to effectively overcome the above mentioned
problem, and to speed up the key search as well. The simplest indexing structure is the single-level
one: a file whose records are pair’s key-pointer, where the pointer is the position in the data file of
the record with the given key. Only a subset of data records, evenly spaced along thedata file, are
indexed, so to mark intervals of data records.

A key search then proceeds as follows: the search key is compared with the index ones to find the
highest index key preceding the search one, and a linear search is performed from the record the index
key points onward, until the search key is matched or until the record pointed by the next index entry
is reached. In spite of the double file access (index + data) needed by this kind of search, the decrease
in access time with respect to a sequential file is significant.

Input:
Algorithmic Steps/Pseudo code/Program:
Sequential search
For each item in the list:
if that item has the desired value,
stop the search and return the item's location.
Return Λ.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Binary Search
int binary_search(int A[], int key, int imin, int imax)
{
// continue searching while [imin,imax] is not empty
while (imax >= imin)
{
// calculate the midpoint for roughly equal partition
int imid = midpoint(imin, imax);
if(A[imid] == key)
// key found at index imid
return imid;
// determine which subarray to search
else if (A[imid] < key)
// change min index to search upper subarray
imin = imid + 1;
else
// change max index to search lower subarray
imax = imid - 1;
}
// key was not found
return KEY_NOT_FOUND;
}
Source Code:
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int arr[100], st, mid, end, i, n, tgt,j,temp;
bool swapped;
cout << " Define the size of the array: " << endl;
cin >> n;

cout << " Enter the values of array " << endl;
for (i = 0; i < n; i++)
{
cout << " arr [" << i << "] = ";
cin >> arr[i];
}

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


{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}
}

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
if (swapped == false)
break;
}
cout<< "sorted array is ";
for (i = 0; i < n; i++)
cout <<" "<< arr[i]<<endl;

st = 0;
end = n - 1;

cout << " Define a value to be searched from sorted array: " << endl;
cin >> tgt;

while ( st <= end)


{
mid = ( st + end ) / 2;
if (arr[mid] == tgt)
{
cout << " Element is found at index " << (mid + 1);
exit (0);
}
else if ( tgt > arr[mid])
{
st = mid + 1;
}

else if ( tgt < arr[mid])


{
end = mid - 1;
}
}
cout << " Number is not found. " << endl;
return 0;
}
Output: Soft copy of program with output.

Conclusion: Thus we have studied searching methods.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT NO: 6
Title: Department maintains student’s database. The file contains roll number, name, division and
address. Write a program to create a sequential file to store and maintain student data. It should allowthe
user to add, delete information of student. Display information of particular student. If record of student
does not exist an appropriate message is displayed. If student record is found it should display the student
details.

AIM/ PROBLEM STATEMENT: Write a program to perform following operations on any


database: Add Delete, Modify, Display, Search & Sort etc.

Prerequisites: Basic Knowledge about file handling operations

Relevant Course Objectives: To learn various file handling operations

Theory:

The file represents a sequence of bytes, does not matter if it is a text file or binary file. Cprogramming
language provides access on high level functions as well as low level (OS level) calls to handle file
on your storage devices.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file, this call will initialize
an object of the type FILE, which contains all the information necessary to control the stream.
Following is the prototype of this function call:

FILE *fopen( const char * filename, const char * mode );

Mode Description

r Opens an existing text file for reading purpose.

Opens a text file for writing, if it does not exist then a new file is created.
w
Here your program will start writing content from the beginning of the file.

Opens a text file for writing in appending mode, if it does not exist then a new
a file is created. Here your program will start appending content in the existing
file content.

r+ Opens a text file for reading and writing both.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

Opens a text file for reading and writing both. It first truncate the file to zero
w+
length if it exists otherwise create the file if it does not exist.

Opens a text file for reading and writing both. It creates the file if it does not
a+ exist. The reading will start from the beginning but writing can only be
appended.

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is:

int fclose( FILE *fp );

The fclose( ) function returns zero on success, or EOF if there is an error in closing the file. This
function actually, flushes any data still pending in the buffer to the file, closes the file, and releases
any memory used for the file. The EOF is a constant defined in the header file stdio.h.

Writing a File

Following is the simplest function to write individual characters to a stream:

int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the output stream referenced by
fp. It returns the written character written on success otherwise EOF if there is an error. You can use
the following functions to write a null-terminated string to a stream:

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced by fp. It returns a non- negative
value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE
*fp,const char *format, ...) function as well to write a string into a file.

Reading a File

Following is the simplest function to read a single character from a file:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by fp. The return value is the
character read, or in case of any error it returns EOF. The following functions allow you to read a
string from a stream:

char *fgets( char *buf, int n, FILE *fp );

The functions fgets() reads up to n - 1 characters from the input stream referenced by fp. It copies the
read string into the buffer buf, appending a null character to terminate the string.
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

If this function encounters a newline character '\n' or the end of the file EOF before they have read
the maximum number of characters, then it returns only the characters read up to that pointincluding
new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read
strings from a file but it stops reading after the first space character encounters.

Input: Algorithmic Steps/Pseudo code/Program:

Writing a File

FILE *fp;

fp = fopen("/tmp/test.txt", "w+");

fprintf(fp, "This is testing for fprintf...\n");

fputs("This is testing for fputs...\n", fp);

fclose(fp);

Reading a File

FILE *fp;

char buff[255];

fp = fopen("/tmp/test.txt", "r");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

Conclusion:

Thus we have studied a program to perform various operations on any database: Add, Delete, Modify,
Display, Search & Sort etc.

Source Code:
#include<bits/stdc++.h>
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
using namespace std;
class tel
{

public:
int rollNo,roll1;
char name[10];
char div;
char address[20];
void accept()
{
cout<<"\n\tEnter Roll Number : ";
cin>>rollNo;
cout<<"\n\tEnter the Name : ";
cin>>name;
cout<<"\n\tEnter the Division:";
cin>>div;
cout<<"\n\tEnter the Address:";
cin>>address;
}
void accept2()
{
cout<<"\n\tEnter the Roll No. to modify : ";
cin>>rollNo;
}
void accept3()
{
cout<<"\n\tEnter the name to modify : ";
cin>>name;
}
int getRollNo()
{
return rollNo;
}
void show()
{

cout<<"\n\t"<<rollNo<<"\t\t"<<name<<"\t\t"<<div<<"\t\t"<<address;
}
};
int main()
{
int i,n,ch,ch1,rec,start,count,add,n1,add2,start2,n2,y,a,b,on,oname,add3,start3,n3,y1,add4,start4,n4;
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
char name[20],name2[20];
tel t1;
count=0;
fstream g,f;
do
{
cout<<"\n>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<";
cout<<"\n1.Insert and overwrite\n2.Show\n 3.Delete a Student Record\n 4.Exit\n\tEnter the
Choice\t:";
cin>>ch;
switch(ch)
{
case 1:
f.open("StuRecord.txt",ios::out);
x:t1.accept();
f.write((char*) &t1,(sizeof(t1)));
cout<<"\nRecord inserted";
cin>>ch1;
if(ch1==1)
goto x;
else
{
f.close();
break;
}

case 2:
f.open("StuRecord.txt",ios::in);
f.read((char*) &t1,(sizeof(t1)));
while(f)
{
t1.show();
f.read((char*) &t1,(sizeof(t1)));
}
f.close();
break;

case 3:
int roll;
cout<<"Please Enter the Roll No. of Student Whose Info You Want to Delete: ";
cin>>roll;
f.open("StuRecord.txt",ios::in);
g.open("temp.txt",ios::out);
VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23
f.read((char *)&t1,sizeof(t1));
while(!f.eof())
{
if (t1.getRollNo() != roll)
g.write((char *)&t1,sizeof(t1));
f.read((char *)&t1,sizeof(t1));
}
cout << "The record with the roll no. " << roll << " has been deleted " << endl;
f.close();
g.close();
remove("StuRecord.txt");
rename("temp.txt","StuRecord.txt");
break;
case 4:
cout<<"\n\tThank you";
break;
}
}while(ch!=4);
}

Output: Soft copy of program with output.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

ASSIGNMENT NO: 7
Title: Case study to Represent graph as adjacency matrix or list and perform Depth first Traversal
and Breadth First Traversal

AIM/ PROBLEM STATEMENT: Represent graph as adjacency matrix or list and perform Depth
first Traversal and Breadth First Traversal

Prerequisites: Knowledge about Graph and Tree

Relevant Course Objectives: To learn the concept of adjacency matrix or list and perform Depth
first Traversal and Breadth First Traversal

Theory:

Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph
representation. In this article, adjacency matrix will be used to represent the graph.

Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix


mat[][] of size n*n (where n is the number of vertices) will represent the edges of the graph where
mat[i][j] = 1 represents that there is an edge between the vertices i and j while mat[i][j] =0
represents that there is no edge between the vertices i and j.

BFS algorithm

A standard BFS implementation puts each vertex of the graph into one of two categories:

1. Visited

2. Not Visited

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The algorithm works as follows:

1. Start by putting any one of the graph's vertices at the back of a queue.

2. Take the front item of the queue and add it to the visited list.

3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the back of the queue.

VIIT, PUNE
DSA Lab Manual SE MECH, Sem-I, 2022-23

4. Keep repeating steps 2 and 3 until the queue is empty.

The graph might have two different disconnected parts so to make sure that we cover every vertex,
we can also run the BFS algorithm on every node

Depth First Search:


DFS, Depth First Search, is an edge-based technique. It uses the Stack data structure and performs
two stages, first visited vertices are pushed into the stack, and second if there are no vertices then
visited vertices are popped.

Depth First Search Algorithm

A standard DFS implementation puts each vertex of the graph into one of two categories:

1. Visited

2. Not Visited

The purpose of the algorithm is to mark each vertex as visited while avoiding cycles.

The DFS algorithm works as follows:

1. Start by putting any one of the graph's vertices on top of a stack.

2. Take the top item of the stack and add it to the visited list.

3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to
the top of the stack.

4. Keep repeating steps 2 and 3 until the stack is empty.


Conclusion:
O(V + E), where V is the number of vertices and E is the number of edges in the graph. The time
complexity of the BFS algorithm is represented in the form of O(V + E), where V is the number of
nodes and E is the number of edges.

VIIT, PUNE

You might also like