0% found this document useful (0 votes)
44 views25 pages

DSAL-assignment No-7-8-9-10

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views25 pages

DSAL-assignment No-7-8-9-10

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

7.

Implementation of Kruskal’s algorithms

AIM: Represent any real world graph using adjacency list /adjacency matrix find minimum
spanning tree using Kruskal‘s algorithm.

OBJECTIVE:
1. Learn the concepts of graph as a data structure and their applications in
everyday life.
2. Understand graph representation (adjacency matrix, adjacency list, adjacency
multi list)

THEORY:
1. What is a graph? Various terminologies and its applications. Explain in brief.
 Definition : A graph is a triple G = (V,E, φ) where
• V is a finite set, called the vertices of G,
• E is a finite set, called the edges of G, and
• φ is a function with domain E and codomain P2(V ).

 Degrees of vertices: Let G = (V,E, φ) be a graph and v ∈ V a vertex. Define


 Loops: A loop is an edge that connects a vertex to itself.

the degree of v, d(v) to be the number of e ∈ E such that v ∈ φ(e); i.e., e is


Incident on v.
 Directed graph: A directed graph (or digraph) is a triple D = (V,E, φ)
where V and E are finite sets and φ is a function with domain E and codomain
V × V . We call E the set of edges of the digraph D and call V the set of vertices
of D.
 Path: Let G = (V,E, φ) be a graph.
Let e1, e2, . . . , en−1 be a sequence of elements of E (edges of G) for which
there is a sequence a1, a2, . . . , an of distinct elements of V (vertices of G)
such that φ(ei) = {ai, ai+1} for i = 1, 2, . . . , n − 1. The sequence of edges e1,
e2, . . . , en−1 is called a path in G. The sequence of vertices a1,
a2, . . . , an is called the vertex sequence of the path.
 Circuit and Cycle: Let G = (V, E, φ) be a graph and let e1, . . . , en be a trail
with vertex sequence a1, . . . , an, a1. (It returns to its starting point.) The
subgraph G′ of G induced by the set of edges {e1, . . . , en} is called a circuit of
G. The length of the circuit is n.

2. Different representations of graph.

 Adjacency matrix: Graphs G = (V, E) can be represented by adjacency


matrices G [v1..v|V |, v1..v|V |], where the rows and columns are indexed by the
nodes, and the entries G [vi, vj] represent the edges. In the case of unlabeled
graphs, the entries are just boolean values.
ABCD
A0 1 1 1
B1 0 0 1
C1 0 0 1
D1 1 1 0

In case of labeled graphs, the labels themselves may be introduced into the entries.

AB C D
A 10 4 1
B 15
C 9
D

 Adjacency List: A representation of the graph consisting of a list of nodes, with


each node containing a list of its neighboring nodes.

Kruskal’s Algorithm:
Step 1: Choose the arc of least weight.
Step 2: Choose from those arcs remaining the arc of least weight which does not
form a cycle with already chosen arcs. (If there are several such arcs, choose one
arbitrarily.)
Step 3: Repeat Step 2 until n – 1 arcs have been chosen.

INPUT:
Enter the no. of nodes in graph. Create the adjacency LIST

OUTPUT:
Display result of each operation with error checking.

INPUT OUTPUT Remark

Cost of
MST - 39
Cost of
MST - 37

FAQS:

1. What is graph?
2. Application of Prim‘s & Kruskal‘s algorithm.
3. What are the traversal techniques?
4. What are the graph representation techniques?
5. What is adjacency Matrix?
6. What is adjacency list?
7. What is adjacency Multi-list?

b) Prim’s Algorithm
AIM: A business house has several offices in different countries; they want to lease
Phone lines to connect them with each other and the phone company charges
different rent to connect different pairs of cities. Business house want to connect all
Its offices with a minimum total cost. Solve the problem by suggesting appropriate
data structures
OBJECTIVES:
1. To understand minimum spanning tree of a Graph
2. To understand how Prim‘s algorithm works

PROBLEM SPECIPICATIONS:
DATA STRUCTURES TO BE USED:
Array: Two dimensional array (adjacency matrix) to store the adjacent vertices & the
weights associated edges.
One dimensional array to store an indicator for each vertex whether visited or not.
#define max 20
int adj_ver[max][max];
int edge_wt[max][max];
int ind[max];

CONCEPTS TO BE USED:
 Arrays
 Function to construct head list & adjacency matrix for a graph.
 Function to display adjacency matrix of a graph.
 Function to generate minimum spanning tree for a graph using Prim‘s algorithm.

THEORY:
 Spanning Tree:
A Spanning Tree of a graph G = (V, E) is a sub graph of G having all vertices of G and no
cycles in it.

Minimal Spanning Tree: The cost of a graph is the sum of the costs of the edges in the
weighted graph. A spanning tree of a graph G= (V, E) is called minimal cost spanning tree
or simply the minimal spanning tree of G if its cost is minimum.

 When a graph G is connected, depth first or breadth first search starting at any
vertex visits all the vertices in G.
 The edges of G are partitioned into two sets i.e. T for the tree edges & B for back
edges. T is the set of tree edges and B for back edges. T is the set of edges
used or traversed during the search & B is the set of remaining edges.
 The edges of G in T form a tree which includes all the vertices of graph G and this
tree is called as spanning tree.

Definition: Any tree, which consists solely of edges in graph G and includes all the
vertices in G, is called as spanning tree. Thus for a given connected graph there are
multiple spanning trees possible. For maximal connected graph having ‗n‘ vertices the
number of different possible spanning trees is equal to n.
Cycle: If any edge from set B of graph G is introduced into the corresponding spanning
tree T of graph G then cycle is formed. This cycle consists of edge (v, w) from the set B
and all edges on the path from w to v in T.

 Prim's algorithm: Prim‘s algorithm is an algorithm in graph theory that finds a minimum
spanning tree for a connected weighted graph. This means it finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the
edges in the tree is minimized. The algorithm was discovered in 1930 by
mathematician Vojtech Jarník and later independently by computer scientist Robert C.
Prim in 1957 and rediscovered by Edsger Dijkstra in 1959. Therefore it is sometimes
called the DJP algorithm, the Jarník algorithm, or the Prim-Jarník algorithm.

An arbitrary node is chosen initially as the tree root (any node can be
considered as root node for a graph). The nodes of the graph are then
appended to the tree one at a time until all nodes of the graph are included.
The node of the graph added to the tree at each point is that node adjacent to a node of
the tree by an arc of minimum weight. The arc of minimum weight becomes a tree arc
containing the new node to tree. When all the nodes of the graph have been added to the
tree, a minimum spanning tree has been constructed for the graph.

Algorithm / Pseudo code:


 Prim’s Algorithm:
All vertices of a connected graph are included in the minimum spanning tree. Prim‘s
algorithm starts from one vertex and grows the rest of tree by adding one vertex at a
time by adding associated edge in T. This algorithm iteratively adds edges until all
vertices are visited.

void prims (vertex i)


1. Start
2. Initialize visited [ ] to 0
for (i=0;i<n; i++)
visited [ i ] = 0;
3. Find minimum edge from i
for (j=0;j<n; j++)
{
if (min > a [i] [j])
{
min = a[i] [j]
x = i;
y = j;
}
}
4. Print the edge between i and j with weight.
5. Make visit [i++] = x
visit [j++] = y
6. Find next minimum edge starting from nodes of visit array.
7. Repeat step 6 until all the nodes are visited.
8. End.

Trace of Prim‘s algorithm for graph G1 starting from vertex 1

Step Set A Set (V-A) Min cost Cost Set B


No. Edge (u,
v)
Initial {1} {2,3,4,5,6,7} -- -- {}
1 {1,2} {3,4,5,6,7} (1, 2) 1 {(1, 2)}
2 {1, 2, 3} {4, 5, 6, 7} (2, 3) 2 {(1,2},(2,3)}
3 {1,2,3,5} {4, 6, 7} (2, 5) 4 {(1,2),(2,3),(2,5)}
4 {1,2,3,5,4} {6, 7} (1,4) 4 {(1,2),(2,3),(2,5),(1,4)}
5 {1,2,3,5,4,7} {6} (4,7) 4 {(1,2),(2,3),(2,5),(1,4),(4,7)}
6 {1,2,3,5,4,7.6} { } (7,6) 3 {(1,2),(2,3),(2,5),(1,4),(4,7),(7,6)}
Total Cost 17
Thus the minimum spanning tree for graph G1 is : A = { 1,2,3,4,5,7,6}
B = {(1,2),(2,3),(2,5),(1,4),(4,7),(7,6)}
Total Weight: 1+2+4+3+4+3=17

INPUT:
Graph entered as an adjacency matrix for n vertices i.e. fill an n*n matrix with the values of
the weights of the edges of the graph where the row number and column number as the
two vertices of one edge.

OUTPUT: Display adjacency matrix for the constructed graph. Display minimum spanning
tree using Prim‘s algorithm.

 Sample Input/Output:

Input: Enter vertices of a graph: 1 2 3 4 5 6 7


Enter vertex wise adjacent vertices & cost of edges.
Vertex Adjacent Vertex Cost
Pune (1) 2 1
4 4
0

Mumbai (2) 1 1

4 6

5 4

3 2
0

Bangalore (3) 2 2
5 5

6 8

Hyderabad (4) 1 4
2 6

5 3
5 3
7 4
0
Chennai (5) 2 4
3 5
6 8
7 7
4 3
0

Delhi (6) 3 8
5 8
7 3
0

Ahmadabad (7) 4 4
5 7
6 3
0

Output: Display of adjacent matrix_adj vertices & cost of associated edges.


Pune (1): (0, 0) (2, 1) (0,0) (4, 4) (0, 0) (0, 0) (0, 0)
Mumbai (2): (1, 1) (0, 0) (3, 2) (4, 6) (5, 4) (0, 0) (0, 0)
Bangalore (3): (0, 0) (2, 2) (0, 0) (0, 0) (5, 5) (6, 8) (0, 0)
Hyderabad (4): (1, 4) (2, 6) (0, 0) (0, 0) (5, 3) (0, 0) (7, 4)
Chennai (5): (0, 0) (2, 4) (3, 5) (4, 3) (0, 0) (6, 8) (7, 7)
Delhi (6): (0, 0) (0, 0) (3, 8) (0, 0) (5, 8) (0, 0) (7, 3)
Ahmadabad (7): (0, 0) (0, 0) (0, 0) (4, 4) (5, 7) (6, 3) (0, 0)

Minimum spanning tree using Prim‘s algorithm:


{(1,2), (2,3), (2,5), (5,4), (4,7), (7,6)}

Total cost: 17

Testing:
Test program for following test cases
For each test case:
a) Display the total number of comparisons required to construct the graph in
computer memory.
b) Display the results as given in the sample o/p above.
c) Finally conclude on time & time space complexity for the construction of the graph
and for generation of minimum spanning tree using Prim‘s algorithm.

Time Complexity:
For the construction of an undirected graph with ‗n‘ vertices and ‗e‘ edges using
adjacency list is O (n + e), since for every vertex ‗v‘ in G we need to store all adjacent
edges to vertex v.
 In Prim‘s algorithm to get minimum spanning tree from an undirected graph with
‗n‘ vertices using adjacency matrix is O(n2).
 Using Kruskal‘s algorithm
using adjacency matrix = O(n2).
using adjacency list=O(eloge)
Pseudo code:
Structure to be used
typedef struct edges
{
int v1,v2,wt;
}edge;

Algorithm acceptgraph (int G[][MAX], int n)


declare int i,j;
print (Enter 0 if no edge is present)
for i=0 to n do
for j=i+1 to n do
print Enter Wt. of edge(V[i], V[j]):
read(G[i][j])
G[j][i]=G[i][j]
end
end
end acceptgraph

 Algorithm for adjacent to edges


Algorithm int AdjToEdges(int G[][MAX], int n, edge E[])
declare int i,j,k=0;
for i=0 to n do
for j=i+1 to n do
if(G[i][j])
E[k].v1=i;
E[k].v2=j;
E[k++].wt=G[i][j];
end if
end for
end for
return k;
end AdjToEdges

 Algorithm to print edges


Algorithm PrintEdges(edge E[], int noe)
{
int i;
for(i=0;i<noe;i++)
{
printf("\n(V%d, V%d)=%d",E[i].v1,E[i].v2,E[i].wt);
}
}
 // Function to sort the edges according to
weights Algorithm SortEdges(edge E[], int noe)
{
int i,j;
edge t;
for(i=0;i<noe;i++)
{
for(j=i+1;j<noe;j++)
{
if(E[i].wt>E[j].wt)
{
t=E[i];
E[i]=E[j];
E[j]=t;
}
}
}
}
 // Function to calculate total cost
Algorithm int total(edge E[], int noe)
{
int i,sum=0;
for(i=0;i<noe;i++)
sum=sum+E[i].wt;
return sum;
}
 Algorithm for sorting the edges according to
weights algorithm int Search(int tv[], int v, int n)
begin:
declare int i;
for i=0 to n dp
if(tv[i]==v)
return(1);

end
end return(0);

 Algorithm PrintAdj(int G[][MAX], int nov)


begin:
declare int i,j;
for i=0to nov do
print V[i]
end
for i=0 to nov do
print ―\nV[i]‖
for j=0 to nov do
printf("%5d",G[i][j]);

end
end
end

 Algorithm to generate spanning tree by Prim's


Algorithm Algorithm prims(int S[ ][MAX],edge E[], int noe):
begin:
declare int TV[MAX], visited[MAX]={0};
declare int i,j,k=0,l,vt1,vt2,v;
declare edge T[20];
TV[k++]=0;
for i=0 to noe do
for j=0 to noe do
if(!visited[j])
vt1=E[j].v1;
vt2=E[j].v2;
if((Search(TV, vt1,k)&&!Search(TV,vt2,k))) S[vt1]
[vt2]=E[j].wt;
S[vt2][vt1]=E[j].wt;
TV[k++]=vt2;
visited[j]=1;
break;
end
else if(Search(TV,vt2,k)&&!Search(TV,vt1,k))
S[vt1][vt2]=E[j].wt;
S[vt2][vt1]=E[j].wt;
TV[k++]=vt1;
visited[j]=1;
break;
end
end if
end for
end for
end Prim
Applications of spanning Trees:
 To find independent set of circuit equations for an electrical network. By adding
an edge from set B to spanning tree we get a cycle and then Kirchoff‘s second
law is used on the resulting cycle to obtain a circuit equation.
 Using the property of spanning trees we can select the spanning tree with (n-1)
edges such that total cost is minimum if each edge in a graph represents cost.
 Analysis of project planning
 Identification of chemical compounds
 Statistical mechanics, genetics, cybernetics, linguistics, social sciences

CONCLUSION:
The cost of spanning tree of graph G is the sum of the costs of the edges in that tree. Any
connected graph with n vertices must have at least n-1 edges and all connected graphs
with n-1 edges are trees.

INPUT:
Enter the no. of nodes in graph. Create the adjacency LIST

OUTPUT:
Display result of each operation with error checking.

INPUT OUTPUT Remark

Cost of
MST - 39

Cost of
MST - 37

FAQS:
1. Explain the PRIM‘s algorithm for minimum spanning tree.
2. What are the traversal techniques?
3. What are the graph representation techniques?
8.Implementation of Dijikstra’s algorithm

AIM: Represent a given graph using adjacency matrix /adjacency list and find the
shortest path using Dijkstra's algorithm (single source all destination).

OBJECTIVE:
1. To understand the application of Dijkstra‘s algorithm

THEORY:
1. Explain in brief with examples how to find the shortest path using Dijkstra‘s
algorithm.

Definition of Dijkstra's Shortest Path

1. To find the shortest path between points, the weight or length of a path is calculated
as the sum of the weights of the edges in the path.
2. A path is a shortest if there is no path from x to y with lower weight.
3. Dijkstra's algorithm finds the shortest path from x to y in order of increasing distance
from x. That is, it chooses the first minimum edge, stores this value and adds the
next minimum value from the next edge it selects.
4. It starts out at one vertex and branches out by selecting certain edges that lead to
new vertices.
5. It is similar to the minimum spanning tree algorithm, in that it is "greedy", always
choosing the closest edge in hopes of an optimal solution.

Example:
It is easiest to think of the geographical distances, with the vertices being places,
such as cities.

Imagine you live in Redville, and would like to know the shortest way to get to the
surrounding towns: Greenville, Blueville, Orangeville, and Purpleville. You would be
confronted with problems like: Is it faster to go through Orangeville or Blueville to get to
Purpleville? Is it faster to take a direct route to Greenville, or to take the route that goes
through Blueville? As long as you knew the distances of roads going directly from one city
to another, Dijkstra's algorithm would be able to tell you what the best route for each of the
nearby towns would be.

 Begin with the source node (city), and call this the current node. Set its value to 0. Set
the value of all other nodes to infinity. Mark all nodes as unvisited.
 For each unvisited node that is adjacent to the current node (i.e. a city there is a direct
route to from the present city), do the following. If the value of the current node plus the
value of the edge is less than the value of the adjacent node, change the value of the
adjacent node to this value. Otherwise leave the value as is.
 Set the current node to visited. If there are still some unvisited nodes, set the unvisited
node with the smallest value as the new current node, and go to step 2. If there are no
unvisited nodes, then we are done.

In other words, we start by figuring out the distance from our hometown to all of the towns
we have a direct route to. Then we go through each town, and see if there is a quicker
route through it to any of the towns it has a direct route to. If so, we remember this as our
current best route.

Step I:
We set Redville as our current node. We give it a value of 0, since it doesn't cost anything
to get to it from our starting point. We assign everything else a value of infinity, since we
don't yet know of a way to get to them.

Step II:
Next, we look at the unvisited cities our current node is adjacent to. This means Greenville,
Blueville and Orangeville. We check whether the value of the connecting edge, plus the
value of our current node, is less than the value of the adjacent node, and if so we change
the value. In this case, for all three of the adjacent nodes we should be changing the value,
since all of the adjacent nodes have the value infinity. We change the value to the value of
the current node (zero) plus the value of the connecting edge (10 for Greenville, 5 for
Blueville, 8 for Orangeville). We now mark Redville as visited, and set Blueville as our
current node since it has the lowest value of all unvisited nodes.
Step III:
The unvisited nodes adjacent to Blueville, our current node, are Purpleville and Greenville.
So we want to see if the value of either of those cities is less than the value of Blueville
plus the value of the connecting edge. The value of Blueville plus the value of the road to
Greenvile is 5 + 3 = 8. This is less than the current value of Greenville (10), so it is shorter
to go through Blueville to get to Greenville. We change the value of Greenville to 8,
showing we can get there with a cost of 8. For Purpleville, 5 + 7 = 12, which is less than
Purpleville‘s current value of infinity, so we change its value as well? We mark Blueville as
visited. There are now two unvisited nodes with the lowest value (both Orangeville and
Greenville have value 8). We can arbitrarily choose Greenville to be our next current node.
However, there are no unvisited nodes adjacent to Greenville! We can mark it as visited
without making any other changes, and make Orangeville our next current node.

Step IV:
There is only one unvisited node adjacent to Orangeville. If we check the values,
Orangeville plus the connecting road is 8 + 2 = 10, Purpleville's value is 12, and so we
change Purpleville's value to 10. We mark Orangeville as visited, and Purpleville is our last
unvisited node, so we make it our current node. There are no unvisited nodes adjacent to
Purpleville, so we're done!
All above steps can be simply put in a tabular form like this:

ALGORITHM:

College Area represented by Graph.


A graph G with N nodes is maintained by its adjacency matrix Cost. Dijkstra‘s algorithm
find shortest path matrix D of Graph G.
Staring Node is 1.
Step 1: Repeat Step 2 for I = 1 to N
D[I] = Cost[1][I].
Step 2: Repeat Steps 3 & 4 for I = 1 to N
Step 3: Repeat Steps 4 for J = 1 to N
Step 4: If D[J] > D[I] + D[I][J]
Then D[J] = D[I] + D[I][J]
Step 5: Stop.

INPUT:
The graph in the form of edges, nodes and corresponding weights, the source node
and destination node.

OUTPUT:
The shortest path and length of the shortest path

INPUT OUTPUT Remark

Shortest Path is Consider Source


A-B-E-F-H-D Vertex as node A
and Destination
Cost - 10 Vertex as node D

FAQs:
1. What is shortest path?
2. What are the graph representation techniques?
3. What is adjacency Matrix?
4. What is adjacency list?
5. What is adjacency Multi-list?
9. Implement Heap sort to sort given set of values using max or
min heap.

AIM: Implement Heap sort to sort a given set of values using max or min heap.

OBJECTIVE:
To understand the concept of a Heap.

THEORY:

Heap Data Structure :

a)Concept
i)Heap Tree
Heap is a binary tree structure with the following properties:
1.The tree is complete or almost complete
2.The key value of each node is greater than or equal to the key value of its
descendants.

(A) (B) (C)


Valid Heap Tree Invalid Heap Tree Invalid Heap Tree
due to sub-tree 10 not nearly complete

ii)Max-Heap
If the key value of each node is greater than or equal to the key value of its
descendants, this heap structure is called Max-Heap.

iii)Min-Heap
If the key value of each node is less than or equal to the key value of its descendants,
this heap structure is called Min-Heap.
b)Maintenance Operations on Heap
To perform insert and delete a node in heap
structure, it needs two basic algorithms :
1.Reheap up
This operation reorders a “broken” heap by floating the last element up the tree until
it is at its correct position in the heap.

Fig. a Fig. b Fig. c


Not a heap tree node 75 moved up node 75 moved
at correct position,
it is heap tree

2.Reheap down
This operation reorders a “broken” heap by pushing the root down the tree until it is
at its correct position in the heap.

Fig. a Fig. b Fig. c


Not a heap tree Moved down node It is heap tree
18 at its correct place (Max heap)

2.Heap Implementation
Heap implementation is possible using an array because it must be a complete or almost
complete binary tree, which allows a fixed relationship between each node and its children
and it can be calculated as :
i. For node located at ith index, its children are :
Left child : 2i + 1
Right child : 2i + 2
ii. Parent of node located at ith index : (i-1)/2
iii. Given the index for a left child, j,its right sibling at : j+1
iv. Given the index for a right child, k, its left sibling at :k-1
3.Heap ADT
4.Applications of Heap
i. Selection algorithm
ii. Priority Queue
iii. Sorting (Heap Sort)
5.Heap Sort Complexity
The Heap sort efficiency is O(n log n)

ALGORITHM:
A. Heapify_asc(data,i)
Step 1 : Set Lt = Left(i)
Step 2 : Set Rt = Right(i)
Step 3 : if Lt <= heap_size[data] - 1 and data[Lt] >
data[i]
then Set Max = Lt;
else
Set Max = i
Step 4 : if Rt <= heap_size[data] - 1 and data[Rt] >
data[Max]
then Set Max = Rt
Step 5 : if Max != i
then Swap(data[i], data[Max])
Step 6 : Heapify(data, Max)

B. BuildHeap(data)
Step 1 : Set heap_size[data] = length[data]
Step 2 : for i= (length[data]-1)/2 to 0
Heapify(data,i)

C. Heapsort(data)
Step 1 : BuildHeap(data)
Step 2 : for i = length[data] - 1 to 1
Swap(data[0],data[i])
Set heap_size[data] = heap_size[data] - 1
Heapify(data,0)

INPUT:
45, 78, 24, 36, 12
10, 28, 56, 68, 75
89, 70, 64, 52,

OUTPUT:

Enter how many elements you want to sort? :45 5

Enter elements :45 78 36 24 12

1. Ascending order
2. Descending order
3. Exit
Enter your choice :1

size = 5 78 45 36 24 12
After building the heap…
Sorted Elements are: 12 24 36 45 78
1. Ascending order
2. Descending order
3. Exit
Enter your choice :2

size = 5 12 24 36 45 78
After building the heap...
Sorted Elements are: 78 45 36 24 12
1. Ascending order
2. Descending order
3. Exit
Enter your choice :3

FAQS:

1. How do you sort an array using heap sort?


2.
10. Implementation of sequential file

Assignment No. 10
Title: File Handling
Aim: To implement program for Sequential Access File
Detailed Problem Statement:
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 allow the 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.
Objective:
To learn Sequential file organization.
Outcome:
1. Analyse algorithms and to determine algorithm correctness.
2. Design algorithms based on techniques like brute -force, divide and conquer,
greedy, etc.).
3. Analyse of algorithms with respect to time and space complexity.
4. Able to learn Sequential File Organization.
Theory
● In order to store data permanently, secondary storage devices like hard disks,
pen drives are used. A file(stream) is a collection of related data stored in a
particular area on the secondary storage devices like hard disk.

File system
Disk

CPU
Keyboard Monitor
RAM

● Basic File operations :


o Open a file
o Read information from the file
o Write information into the file
o Close a file

● Different ways to access file


o Sequential Access File – Information is being read sequentially from
the beginning of file. ( eg. In order to access/read 10th record from the
file, we need to read first 9 records)
o Direct Access File – The record can be accessed directly, without
accessing any previous record.
File classes :
Class Functions Meaning
ifstream open() Open the file in default input mode(read from file)
get() ios::in
getline() Read one character from the file
read() Read one complete line from the file
tellg(), seekg() Read any type of data from the file
Direct access file functions(not required for this
assignment)
ofstream open() Open the file in default output mode(write into
put() file)ios::out
write() Write one character into the file
tellp(), seekp() Write any type of data into the file
Direct access file functions(not required for this
assignment)
fstream Inherits all above Provides support for simultaneous input and output
functions through operations. Ios::in|ios::out
iostream

ADT :
1. 2. 3.
struct student struct DoB class seqfile
{ { {
Int stud_rollno; int stud_day; student stud_rec;
char stud_name[30]; int stud_month; ostream outfile;
char stud_division; int stud_year; istream infile;
char stud_address[30]; }
DoB stud_DoB; public:
float stud_percent; void create();
char stud_grade; void display(key);
} void add();
void
search(key);
Void modify(key);
void delete(key);
}

Pseudo codes:
Note : StudentData is file a name
1. Create a file

BEGIN CreateAFile
Open StudentData for output

Display “Please enter the information of student: ”


Get rollno,name,divison,address,date of birth,percentage,grade
Write rollno,name,divison,address,date of birth,percentage,grade into
StudentData

Close StudentData
END CreateAFile

2. Display a file

BEGIN DisplayFileContents
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF

WHILE Not EndofFile StudentData


Read Student Information from StudentData
Display Student Information
END WHILE
Close StudentData
END DisplayFileContents

3. Add a record

BEGIN AddNewRecords
Open StudentData for append // file pointer will automatically moved to the end of
file

IF FileNotPresent
Display error message
Exit
END IF

Display “Please enter the information of student: ”


Get rollno,name,divison,address,date of birth,percentage,grade
Write rollno,name,divison,address,date of birth,percentage,grade into
StudentData

Close StudentData
END AddNewRecords
4. Search a record

BEGIN SearchRecord(key)
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF

WHILE Not EndofFile StudentData


Read Student Information from StudentData
IF StudentRecord contains key //key can be unique roll no or if ‘name’ there can
be multiple records displayed
Display Student Information
ENDIF
END WHILE
Close StudentData
END SearchRecord

5. Modify a Record

BEGIN ModifyRecord(key)
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF
Open Temporary file for output
WHILE Not EndofFile StudentData
Read Student Information from StudentData
IF StudentRecord contains key //key should be unique as ‘roll no’
Display Student Information
Get new information for modification
Write information into Temporary file
ELSE
Write information into Temporary file
ENDIF
END WHILE
Delete StudentData
Rename Temporary File as StudentData
Close StudentData
END ModifyRecord

6. Delete a Record

BEGIN ModifyRecord(key)
Open StudentData for input
IF FileNotPresent
Display error message
Exit
END IF
Open Temporary file for output
WHILE Not EndofFile StudentData
Read Student Information from StudentData
IF StudentRecord contains key //key should be unique as ‘roll no’
Continue // read next record
ELSE
Write information into Temporary file
ENDIF
END WHILE
Delete StudentData
Rename Temporary File as StudentData
Close StudentData
END ModifyRecord

Test Cases:
1. Open a file in reading mode which does not exist.
2. Open a file in writing mode which is already exist.
3. Search /Modify/Delete record with no key present.
4. Not able to open a new file.
5. We may have invalid file name.

Conclusion : All file handling functions are implemented for sequential file
organization and the results generated as per requirements.

FAQs:

1. Which header file is required to use file I/O operations?


2. Which class is used to create an output stream?
3. Which class is used to create a stream that performs both input and output
operations?
4. By default, all the files in C++ are opened in _________ mode.
5. What is the use of ios::trunc mode?
6. What is the return type of open() method?
7. Which is the default mode of the opening using the fstream class?
8. Which is the default mode of the opening using the ifstream class?

You might also like