You are on page 1of 55

R. V.

COLLEGE OF ENGINEERING
(Autonomous Institution Affiliated to VTU, Belagavi)
Department of Information Science &
Engineering
Bengaluru, Karnataka 560059

Lab Manual for III semester B.E

Data Structures and File


Structures
16IS35
Faculty In-charge
Prof. CHETHANA R MURTHY
Assistant Professor
Prof. KAVITHA S N
Assistant Professor

USN:

NAME:

Academic Year: 2017-18


Data Structures and File Structures 16IS35

R. V. COLLEGE OF ENGINEERING
(Autonomous Institution Affiliated to VTU, Belagavi)
Department of Information Science & Engineering
Bengaluru, Karnataka 560059

CERTIFICATE

This is to certify that Mr./Ms


USN . of III semester Department of Information Science
and Engineering Branch has satisfactorily completed the course of experiments in
DATA STRUCTURES AND FILE STRUCTURES LABORATORY prescribed by the
university in the academic year 2017 2018.

MARKS

MAXIMUM OBTAINED

RECORD (30m)

TEST (20m)

Total (Max 50m)

Signature of the Student Signature of the Faculty In - Charge Signature of HOD

Dept. of ISE, RVCE 1


Data Structures and File Structures 16IS35

R. V. COLLEGE OF ENGINEERING
(Autonomous Institution Affiliated to VTU, Belagavi)
Department of Information Science & Engineering
Bengaluru, Karnataka 560059
Data Structures and File Structures - 16IS35

PARTICULARS OF THE EXPERIMENT


Program Page Date of Marks Signature
Week Program
No. No. Execution (10) of Staff
1 1 Stack ADT program

2 2 Stack application program

3 3 Queue ADT program

4 4 Queue application program

5 5 Linked list ADT program

6 6 Linked list application program

7 7 Graph ADT program

8 8 Tree ADT program

9
9 Graph, Tree application program

10 Basic file operations program


10
Simple hashing for files with
11 records program

11 12 File structures program

12
Lab Internals

Dept. of ISE, RVCE 2


Data Structures and File Structures 16IS35

INDEX

SL No. Program Title Page No.


General Guidelines 5

Dos and Donts 5

List of lab programs for the course 6

Rubrics for Data Structures and File Structures Lab 7

1 Stack ADT program 8

2 Stack application program 8

3 Queue ADT program 13

4 Queue application program 13

5 Linked list ADT program 19

6 Linked list application program 19

7 Graph ADT program 25

8 Tree ADT program 29

9 Graph, Tree application program 29

10 Basic file operations program 36

11 Simple hashing for files with records program 41

12 File structures program 41

Appendix A Sample viva questions 49

Appendix B Basic commands of vi 50

Appendix C Basic commands of gdb 52

Dept. of ISE, RVCE 3


Data Structures and File Structures 16IS35

Scheme of Continuous Internal Evaluation for Practicals:

LAB INTERNALS

RECORD : 30 Marks

TEST: 20 Marks

Total : 50 Marks

Scheme of Semester End Examination for Practicals:

Total Marks : 50

This includes:
Program Write-up, Execution, and Results : 40
Viva Voce :10

Dept. of ISE, RVCE 4


Data Structures and File Structures 16IS35

R.V. COLLEGE OF ENGINEERING, BANGALORE 560059


(Autonomous Institution Affiliated to VTU, Belgaum)
Department of Information Science & Engineering
Data Structures and File Structures (16IS35)
Laboratory Component

General Guidelines

Use only vi editor.


No IDEs are allowed.GDB should be used for debugging.
GOTO statements and global declarations are not allowed.
Prototype for each user-defined function must be provided before
main.
main should be the first function in any program
Students are encouraged to use user-defined header files.
Programs must be indented appropriately.
Students are encouraged to try implementing the program requirements
using different approach/data structure.

Dos and Donts in the Laboratory


Dos..
Come prepared to the lab with the necessary algorithms, which helps in getting better
solutions.
Use the computers for academic purposes only.
Following the lab exercise cycles as per the instructions given by the department.
Keep the chairs back to their position before you leave.
Handle the computer and the kits with care.
Keep your lab clean.
Donts..
Coming late to the lab and leaving the lab early.
Move around in the lab during the lab session.
Download or install any software onto the computers.
Tamper system files or Try to access the server.
Write Data sheets or Records in lab.
Change the system assigned to you without the notice of lab staff.
Carrying CDs, Floppys, Pen Drives and other storage devices into lab.
Using others login ids.

Dept. of ISE, RVCE 5


Data Structures and File Structures 16IS35

R.V. COLLEGE OF ENGINEERING, BENGALURU 560059


(Autonomous Institution Affiliated to VTU, Belagavi)

Data Structures and File Structures 16IS35


CIE Marks (Lab) : 50 SEE Marks (Lab) : 50
Hrs /Week : 3 SEE Hours : 03

Students are required to implement following programs using C/C++.

Part A (Compulsory)
1. Implementation of integer stack ADT using arrays
2. Implementation of integer queue ADT using arrays
3. Implementation of integer List ADT
4. Implementation of Graph ADT using List
5. Implementation of tree ADT using List
6. Implementation of basic operation on Files.
7. Implementation of simple hash algorithm for files with records.
Part B

At-least one application from each of the following group.

Application of Stack
Implementation of Infix to Postfix conversion
Implementation of Infix to Prefix conversion
Implementation of postfix evaluation
Implementation of prefix evaluation
Application of Queue
Implementation of Priority queue program using array.
Implementation of multiple stacks and queues
Implementation of Johnsons Algorithm
Implementation of maze problem
Application of List
Implementation of sparse matrix multiplication.
Implementation of polynomials operations (addition, subtraction) using Linked List.
Implementation of Linked Lists menu driven program (stack and queue)
Implementation of Double ended queue using Linked Lists.
Application of Graph & Tree
Implementation of construction of expression tree using postfix expression.
Implementation of various operations on tree like copying tree, mirroring a tree, counting the
number of nodes in the tree, counting only leaf nodes in the tree.
Implementation of dictionary using Binary Search Tree
Implementation of Longest Prefix Matching.
Implementation of Binary Heap program
Programs in File Structures
Implementation of Open addressing technique
Implementation of separate chaining with linked list
Implementation of B-Tree
Implementation of secondary index on set of Records
CIE/SEE Evaluation: One Question from Part A, and relevant application from Part B has to be
executed. Weightage for Part A will be 70% and Part B will be 30%.

Dept. of ISE, RVCE 6


Data Structures and File Structures 16IS35

Rubrics for Data Structures and File Structures Lab


Each program is evaluated for 10 marks Write up & Execution = 7 Marks, Viva Voce = 3 Marks

Lab Write-up and Execution rubrics (Max: 7 marks)

Sl Criteria Measuring methods Excellent Good Poor CO


no
Student exhibits Student has sufficient Student does not
1 Understanding of thorough understanding of have clear CO1
problem and Observations understanding of program understanding of
requirements program requirements and program
requirements and applies data structure requirements
(2 Marks) applies data concepts with and is unable to
structure concepts C/C++. apply data
with C/C++. ( 1M) structure
(2M) concepts with
C/C++ .
(0M)
Student Student demonstrates Student has not
2 Execution demonstrates the the execution of the executed the CO3
Observations execution of the program without program.
(3Marks) program with optimization of the (0 M)
optimized code code and handles
with all the only few test cases.
necessary (2M-1M)
conditions and test
cases handled.
(3M)
Documentation Documentation with Documentation
3 Results and with appropriate only few comments with no CO4
Documentation Observations comments and and only few output comments and
output is covered cases is covered in no output cases
(2Marks) in data sheets and data sheets and is covered in
manual. manual. data sheets and
(2M) (1M) manual.
(0 M)

Viva Voce rubrics (Max: 3 marks)


1 Conceptual Explains data Adequately explains Unable to
Understanding and structure concepts the data structure explain the CO1
Communication of Viva Voce with C/C++ and concepts with C/C++ concepts.
concepts related concepts and related concepts (0M)
involved. involved.
(2 Marks) (2M) (1M)

2 Use of appropriate Insightful Sufficiently explains Unable to


Design Techniques explanation of the use of explain the CO3
Viva Voce appropriate design appropriate design design
(1 Mark) techniques for the techniques for the techniques for
given problem to given problem to the given
derive solution. derive solution. problem.
(1 M) (0.5 M) (0 M)

Dept. of ISE, RVCE 7


Data Structures and File Structures 16IS35

Program No. 1& 2

Details of the concept on which the program is given


Stacks
A stack is defined as a special type of data structure where items are inserted from one end
called top of stack and items are deleted from top of the stack. Here, the last item inserted
will be on top of stack. Since deletion is done from the same end, Last item Inserted is the
First item to be deleted Out from the stack and so, stack is also called Last In First Out
(LIFO) data structure.

ADT Mathematical Model Operations

Push(S,Data)
Pop(S)
Stack
Empty(S)
Top(S)

The mathematical model of a stack is LIFO (last in, first out). Data placed in the stack is
accessed through one path. The next available data is the last data to be placed in the stack. In
other words, the "newest" data is withdrawn.
The standard operations on a stack are as follows:
PUSH(S, Data) : Put 'Data' in stack 'S'
POP(S) : Withdraw next available data from stack 'S'
Returns boolean value 'True' if stack 'S' is empty; returns
EMPTY(S) :
'False' otherwise
Views the next available data on stack 'S'.
TOP(S) : This operation is redundant since one can simply POP(S),
view the data, then PUSH(S,Data)

Program question

1. Implement integer stack ADT using arrays

The given question demands a stack ADT to be implemented using arrays. A stack is
structured, as described above, as an ordered collection of items where items are added to and
removed from the end called the top. Stacks are ordered LIFO. The stack abstract data type
must be defined by the following structure and operations:
Stack( ): creates a new stack that is empty. It needs no parameters and returns an
empty stack.

Dept. of ISE, RVCE 8


Data Structures and File Structures 16IS35

push(item): adds a new item to the top of the stack. It needs the item and returns
nothing.
pop(): removes the top item from the stack. It needs no parameters and returns the
item. The stack is modified.
peek(): returns the top item from the stack but does not remove it. It needs no
parameters. The stack is not modified.
isEmpty(): tests to see whether the stack is empty. It needs no parameters and returns
a boolean value.
size(): returns the number of items on the stack. It needs no parameters and returns an
integer.
display( ):displays the contents of the stack from top. The stack is not modified.
Student is encouraged to implement the ADT and create it as a library for future usage.

ALGORITHM of the program


Insert an item into the stack
Algorithm push ( item )
if top = = maximum capacity of the stack then
stack overflow
else
top top + 1
S[top] item
end if-else
end Algorithm

Delete an item from the stack


Algorithm pop ( )
if top = = -1 then
stack underflow
else
item S[top] /* item is the deleted element */
top top 1
end if-else
end Algorithm

Display the contents of the stack.


Algorithm display ( )
if top = = -1 then
stack empty
else
for itop to 0
print S[ i ]
end for
end if-else
end Algorithm
Applications of Stack: The various stack applications are:

Dept. of ISE, RVCE 9


Data Structures and File Structures 16IS35

Reversing data (say string), Palindrome check


Backtracking
Recursion
Converting decimal to binary
Infix to postfix conversion
Infix to prefix conversion
Evaluating postfix expression
Evaluating prefix expression

Objective / purpose of the program:

To implement stack ADT


Application of stack

EXPECTED OUTPUT

Must be able to create an empty stack


Must be able to store elements in the stack
Must be able to display the stack contents, keeping the contents undisturbed
Pop one element at a time from the stack
Must be able to check if the stack is empty or not
Must be able to display the topmost content of the stack without actually modifying
the stack.

CHECK FOR ANY EXCEPTIONAL CONDITIONS

Stack overflow
Stack underflow

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics
Signature
Understanding Execution Results and Conceptual Use of TOTAL of the
of problem (3) Documentation Understanding appropriate (10) Faculty
(2) (2) and Design
Communication Techniques
of Concepts (1)
(2)

Dept. of ISE, RVCE 10


Data Structures and File Structures 16IS35

Program No. 1

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 11


Data Structures and File Structures 16IS35

Program No. 2

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 12


Data Structures and File Structures 16IS35

Program No. 3 & 4

Details of the concept on which the program is given

Queue
A Queue is data structure where elements are inserted from one end and elements are deleted
from the other end. The end from where the elements are inserted is called rear end and the
end from where the elements are deleted is called front end. Since the first item inserted is the
first item to be deleted from the queue, it is called as First In First Out (FIFO).

ADT Mathematical Model Operations

insertQ(Q,
data)
deleteQ(Q)
Queue
Front(Q)
Rear(Q)
emptyQ(Q)

The mathematical model of a queue is FIFO (first in, first put). Data placed in the queue goes
through one path, while data withdrawn goes through another path at the "opposite" end of
the queue. The next available data is the first data placed in the queue. In other words, the
"oldest" data is withdrawn.
The standard operation on a queue are as follows:
INSERTQ(Q, Data) Put 'Data' in the rear path of queue 'Q'
DELETEQ(Q) : Withdraw next available data from front path of queue
'Q'
FRONT(Q) : Views the next available data on queue 'Q'
REAR(Q) : Views the last data entered on queue 'Q'
EMPTYQ(Q) : Check is the queue 'Q' is empty.

Since a queue is a linear collection or linear list in which insertion can take place only at one
end, called rear of the list, and deletions can take place only at other end, if the last position
of the queue is occupied then it is not possible to insert any more elements in the queue even
though some positions are vacant towards the front position of the queue. For example:

Dept. of ISE, RVCE 13


Data Structures and File Structures 16IS35

The limitation of linear queue is overcome by the circular queue. Circular queue is a linear
data structure as a linear queue in the form of circle.

Program question

3. Implement integer queue ADT using arrays

The given question demands a queue ADT to be implemented using arrays. A queue is
structured, as described above, as an ordered collection of items where items are added to and
removed from the end called the rear and front respectively.Queues are ordered FIFO.
The queue abstract data type must be defined by the following structure and operations:
Queue( ): creates a new queue that is empty. It needs no parameters and returns an
empty queue.
insertQ(item): adds a new item at the rear end of the queue. It needs the item and
returns nothing.The queue is modified.
deleteQ(): removes the item from the front end of the queue. It needs no parameters
and returns the item. The queue is modified.
peekFront( ): returns the front end item from the queue but does not remove it. It
needs no parameters. The queue is not modified.
isEmpty(): tests to see whether the queue is empty. It needs no parameters and
returns a boolean value.
size( ): returns the number of items on the queue. It needs no parameters and returns
an integer.
display( ):displays the contents of the queue from rear end. The queue is not
modified.

Student is encouraged to implement the ADT and create it as a library for future usage.

ALGORITHM of the program

Insert an item into circular queue


Algorithm insertQ ( item )
if rear = = Qsize 1 then
Queue overflow
else
rear rear + 1
Q[rear] item
end if-else
end Algorithm

Delete an item from the circular queue

Dept. of ISE, RVCE 14


Data Structures and File Structures 16IS35

Algorithm deleteQ ( )
if rear = = front then
Queue underflow: exit
else
front front + 1
itemQ[front] /* item is the deleted element */

if front = =rear /*queue is empty, reset front and rear to -1 */


front rear -1
end if
end if-else
end Algorithm

Display the content of the queue


Algorithm displayQ( )
if rear = = front
Queue empty: exit
else
for i front+1 to rear
display Q[i]
end for
end if-else
end Algorithm

Check if the queue is full


Algorithm isQfull ( )
if rear = = QSize -1 then
Queue overflow
end if
end Algorithm

Check if the queue is empty


Algorithm isQempty ( )
if rear = = front
Queue empty
end if
end Algorithm

Applications of Queue: The various queue applications are:


Resource scheduling
Breadth First Search
Buffering
Implementation of Priority queue program using array.
Implementation of multiple stacks and queues
Implementation of Johnsons Algorithm
Implementation of maze problem

Dept. of ISE, RVCE 15


Data Structures and File Structures 16IS35

Objective / purpose of the program:

To implement queue ADT


Application of queue

EXPECTED OUTPUT

Must be able to create an empty queue


Must be able to store elements in the queue
Must be able to display the queue contents, keeping the contents undisturbed
Remove one element at a time from the queue
Must be able to check if the queue is empty or not
Must be able to display the content of the queue without actually modifying the
queue.

CHECK FOR ANY EXCEPTIONAL CONDITIONS

Queue full
Queue empty

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics
Signature
Understanding Execution Results and Conceptual Use of TOTAL of the
of problem (3) Documentation Understanding appropriate (10) Faculty
(2) (2) and Design
Communication Techniques
of Concepts (1)
(2)

Dept. of ISE, RVCE 16


Data Structures and File Structures 16IS35

Program No. 3

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 17


Data Structures and File Structures 16IS35

Program No. 4

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 18


Data Structures and File Structures 16IS35

Program No. 5 & 6

Details of the concept on which the program is given

Linked list
Linked list is a dynamic data structure whose length can be varying dramatically as elements
are inserted and removed. Linked list are different from arrays:
An array is a static data structure. This means the length of array cannot be altered at run
time. While, a linked list is a dynamic data structure.
In an array, all the elements are kept at consecutive memory locations while in a linked list
the elements (or nodes) may be kept at any location but still connected to each other.
Linked lists are preferred mostly when we dont know the volume of data to be stored. For
example: In an employee management system, one cannot use arrays as they are of fixed
length while any number of new employees can join. In scenarios like these, linked lists (or
other dynamic data structures) are used as their capacity can be increased (or decreased) at
run time (as and when required).

Program question

5. Implement integer Linked List ADT

Linked list basically consists of memory blocks nodes that are located at random memory
locations and connected through pointers. Usually a block in a linked list is represented
through a structure like this:
struct node {
int info;
struct node *next;
};
A linked list can be organized as a singly linked list, circular list, doubly linked list, circular
doubly linked list etc. Each of the list types has their own advantages and limitations.

The linked list abstract data type must be defined by the following structure and operations:
CreateL( ): creates a new linked list that is empty. It needs no parameters and returns
an empty linked list.
AddL(item): adds a new item at the end of the linked list. It needs the item and
returns nothing.The list is modified.
removeL(): removes the item from the end of the linked list. It needs no parameters
and returns the item. The linked list is modified.

Dept. of ISE, RVCE 19


Data Structures and File Structures 16IS35

searchL( element): returns true if the given element is present in the linked list, else
false. The linked list is not modified.
isEmpty(): tests to see whether the linked list is empty. It needs no parameters and
returns a boolean value.
traverse( ):displays/traverses the contents of the linked list from the beginning. The
linked list is not modified.
Student is encouraged to implement the ADT and create it as a library for future usage.

ALGORITHM of the program


create a new node:
Algorithm getnode ( data )
temp malloc (sizeof(struct node))
info ( temp ) data
next ( temp ) NULL
return temp
end Algorithm

free an existing node:


Algorithm freenode ( p )
free(p)
end Algorithm

Add node at the end of the linked list.


Algorithm AddL ( item )
newNode getnode( item )
if head = = NULL then
head newNode
else
temp head
while ( next( temp ) != NULL )
temp next( temp )
next (temp) newNode
end if-else
end Algorithm

Add node at the end of the linked list.


Algorithm removeL ( )
if head = = NULL then
List empty: exit
else
temp head
while ( next(next( temp )) != NULL )
temp next( temp )
p next(temp)
freenode (p)
next (temp) NULL
end if-else

Dept. of ISE, RVCE 20


Data Structures and File Structures 16IS35

end Algorithm

display the linked list contents


Algorithmtraverse ( )
temp head
while ( temp != NULL)
print info( temp )
temp next( temp )
end while
end Algorithm

Applications of Linked list: The various linked list applications are:


Hash table
Implementation oftree, graph problems
Implementation of sparse matrix multiplication.
Implementation of polynomials operations (addition, subtraction) using Linked List.
Implementation of Linked Lists menu driven program (stack and queue)
Implementation of Double ended queue using Linked Lists.

Objective / purpose of the program

To implement linked list ADT


Application of linked list

EXPECTED OUTPUT

Must be able to create singly linked list for the some elements
Traverse the linked list
Must be able to add/remove elements to/from the linked list

CHECK FOR ANY EXCEPTIONAL CONDITIONS

Empty list
Encourage students to handle the case of duplicate elements

Dept. of ISE, RVCE 21


Data Structures and File Structures 16IS35

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics
Signature
Understanding Execution Results and Conceptual Use of TOTAL of the
of problem (3) Documentation Understanding appropriate (10) Faculty
(2) (2) and Design
Communication Techniques
of Concepts (1)
(2)

Dept. of ISE, RVCE 22


Data Structures and File Structures 16IS35

Program No. 5

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 23


Data Structures and File Structures 16IS35

Program No. 6

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 24


Data Structures and File Structures 16IS35

Program No. 7

Details of the concept on which the program is given

Graph:
Graph is a non-linear data structure. Informally graph is defined as a collection of points
called vertices, some of which are connected by line segments called edges. Graph is a
mathematical structureand finds its application is many areas, where the problem is to be
solved by computers. Graph can be used to model real-life problems like: modeling WWW,
communication networks, project scheduling etc.
Formal definition: A graph G(V, E) consists of a set V of vertices and a set E of pairs of
distinct vertices from V. These pairs of vertices are called edges. If the pairs of vertices are
unordered, G is an undirected graph. If the pairs of vertices are ordered, G is a directed graph
or digraph. A graph with every pair of its vertices connected by an edge is called complete.

Program question

7.Implement Graph ADT using linked list

The problems related to graph G must be represented in computer memory using any suitable
data structure to solve the same. There are two standard ways of maintaining a graph G in the
memory of a computer.
Graph representations:
1. Sequential representation of a graph using adjacency matrix:
A graph G(V, E) with n vertices, is a n X n matrix. The element on the ith row and jth
column is non-zero if theres an edge from ith vertex to the jth vertex; otherwise 0.
2. Linked representation of a graph using adjacency linked list:
A graph is represented as a collection of linked lists, one for each vertex, that contain
all the vertices adjacent to the lists vertex.

Fig 7.1: Undirected graph with 5 vertices Fig 7.2: Adjacency matrix representation of
graph in fig 7.1

Dept. of ISE, RVCE 25


Data Structures and File Structures 16IS35

Fig 7.3: Adjacency linked list representation of graph in fig 7.1

The Graph abstract data type using linked list must be defined by the following structure and
operations:
CreateL(headptr ): creates a new linked list that is empty, and makes the headptr
point to the empty list.
AddNode(headptr, item): adds a new item at the end of the linked list pointed by
headptr. It needs the headptr and the item. It returns nothing.The list is modified.
searchNode( headptr, element): returns true if the given element is present in the
linked list pointed by headptr, else false. The linked list is not modified.
isEmpty(headptr): tests to see whether the linked listpointed by headptr is empty. It
needs no parameters and returns a boolean value.
traverse( headptr):displays/traverses the contents of the linked list pointed by
headptr, from the beginning. The linked list is not modified.
Student is encouraged to implement the ADT and create it as a library for future usage.

ALGORITHM of the program


The node structure can be defined as follows:
struct node {
int info;
struct node *next;
};
create a new node:
Algorithm getnode ( item )
temp malloc ( sizeof ( struct node ) )
info( temp ) item;
next( temp ) NULL
return temp
end Algorithm

create list by inserting node at the end.


Algorithm createList( headptr, item )
newNodegetnode( item )
ifheadptr = NULL then
headptrnewNode

Dept. of ISE, RVCE 26


Data Structures and File Structures 16IS35

else
temp headptr
while( next( temp ) !=NULL)
temp next( temp )
end while
next (temp) newNode
end if-else
end Algorithm

display the linked list contents


Algorithm display ( head )
if head = NULL then
Empty list
else
temp head
while ( temp != NULL )
print info( temp )
temp next( temp )
end while
end if-else
end Algorithm

Objective / purpose of the program

To implement Graph ADT


EXPECTED OUTPUT

Must be able to represent an undirected/directed graph using adjacency linked list


Traverse the adjacency linked list

CHECK FOR ANY EXCEPTIONAL CONDITIONS

Empty list
Encourage students to handle the case of duplicate elements

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics

Understanding Execution Results and Conceptual Use of Signature


of problem (3) Documentation Understanding appropriate
(2) (2) and Design TOTAL of the
Communication Techniques (10) Faculty
of Concepts (1)
(2)

Dept. of ISE, RVCE 27


Data Structures and File Structures 16IS35

Program No. 7

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 28


Data Structures and File Structures 16IS35

Program No. 8 & 9

Details of the concept on which the program is given

Tree:
A tree is anon-linear data structures. It is an acyclic, connected graph defined as a nonempty
finite set of labeled nodes such that there is only one node called the root of the tree, and the
remaining nodes are partitioned into sub trees.

Binary tree:
If the tree is either empty or each of its nodes has not more than two sub trees, it is called a
binary tree. Hence each node in a binary tree has either no children, one left child, one right
child, or a left child and a right child, each child being the root of a binary tree called a sub
tree. Every node in a binary tree contains information divided into three parts. They are key
field, a left-child field, and a right-child field. If a node does not have a right child or a left
child then the corresponding field is set to NULL.

Binary Search Tree


A binary search tree (BST), also known as an ordered binary tree, is a node-based data
structure in which each node has no more than two child nodes. Each child must either be a
leaf node or the root of another binary search tree. The left sub-tree contains only nodes with

Dept. of ISE, RVCE 29


Data Structures and File Structures 16IS35

keys less than the parent node; the right sub-tree contains only nodes with keys greater than
the parent node.

Tree Traversal:
A tree traversal is a specific order in which to trace the nodes of a tree. In a traversal of a tree,
each element of the tree is visited exactly once.
There are three tree traversal methods:
preorder,
inorder, and
postorder.

Program question

8. Implement tree ADT using linked list

The program requires creation of a tree (binarytree) with n elements. Provide routine to insert
a new element into the binary tree, a routine to delete a given element from the binary tree
and routines for tree traversal.

The tree abstract data type must be defined by the following structure and operations:
CreateEmptyTree( ): creates a new binary tree that is empty. It needs no parameters
and returns an empty binary tree.
setLeft(nptr, item): creates a new node with the new item and adds it as the left child
to the node pointed by nptr. It needs the nptr and item, returns nothing.The tree is
modified.
setRight(nptr, item): creates a new node with the new item and adds it as the right
child to the node pointed by nptr. It needs the nptr and item, returns nothing.The tree
is modified.
removeNode(nptr): removes the node pointed by nptr from the tree. It needs pointer
to the node getting deleted and returns modified tree. The tree is modified.
searchNode( nptr, element): returns true if the given element is present in the tree
pointed by nptr, else false. The tree is not modified.
isEmpty(nptr): tests to see whether the tree pointed by nptr is empty. It needs pointer
to the tree as parameter and returns a boolean value.
traverse(nptr):displays/traverses the contents of the tree pointed by npt. The
traversal begins from root. The linked list is not modified.
Student is encouraged to implement the ADT and create it as a library for future usage.

Dept. of ISE, RVCE 30


Data Structures and File Structures 16IS35

ALGORITHM of the program

create binary tree


/* read the first number and insert it into a single node binary tree */
number first number read
tree maketree ( number )
while ( there are numbers left in the input )
number read the next number
p q tree
while( number != info( p ) AND q != NULL )
pq
if left( p ) then
q left( p)
else
q right( p )
end while
/* insert number to the right or left of p */
if left(p)
setleft( p, number )
else
setright( p, number )
end if-else
end while

inorder traversal
Algorithm inorder( t )
if t != NULL then
Traverse the left subtree in inorder
Visit the root
Traverse in right subtree in inorder
end if
end Algorithm

preorder traversal
Algorithm preorder( t )
if t != NULL then
Visit the root
Traverse the left subtree in preorder
Traverse in right subtree in preorder.
end if
end Algorithm

postorder traversal
Algorithm postorder( t )
if t != NULL then
Traverse the left subtree in postorder
Traverse in right subtree in postorder.
Visit the root.

Dept. of ISE, RVCE 31


Data Structures and File Structures 16IS35

end if
end Algorithm

delete a given node z from the binary search tree


case 1:z has no children
delete z by making parent of z point to NULL
case 2:z has one child
delete z by making the parent of z point to zs child, instead of to z
case 3: z has two children
zs successor: y is the minimum node in zs right subtree
y has either no children or one right child (but no left child)
Delete y from the tree (via Case 1 or 2)
Replace zs key and satellite data with ys.

Applications of Graph and Tree: The various applications are:


Representing hierarchical data
Storing data in a way that makes it efficiently searchable
Representing sorted lists of data
As a workflow for compositing digital images for visual effects
Routing algorithms
Implementation of construction of expression tree using postfix expression.
Implementation of various operations on tree like copying tree, mirroring a tree,
counting the number of nodes in the tree, counting only leaf nodes in the tree.
Implementation of dictionary using Binary Search Tree
Implementation of Longest Prefix Matching.
Implementation of Binary Heap program

Objective / purpose of the program

To implement Tree ADT


Application of Graph and Tree

EXPECTED OUTPUT

Must be able to create a binary tree for given n elements


Display the binary tree contents
Traverse the tree in inorder, preorder, postorder
Deleting element can be
case 1: leaf node
case 2: node with either left or right child
case 3: node with both child -intermediate node

Dept. of ISE, RVCE 32


Data Structures and File Structures 16IS35

CHECK FOR ANY EXCEPTIONAL CONDITIONS

empty tree
empty tree traversals
deleting from an empty tree
deleting an non existing element from the tree
students are encouraged to implement the recursive version of the algorithms

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics
Signature
Understanding Execution Results and Conceptual Use of TOTAL of the
of problem (3) Documentation Understanding appropriate (10)
(2) (2) and Design
Faculty
Communication Techniques
of Concepts (1)
(2)

Dept. of ISE, RVCE 33


Data Structures and File Structures 16IS35

Program No. 8

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 34


Data Structures and File Structures 16IS35

Program No. 9

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 35


Data Structures and File Structures 16IS35

Program No. 10

Details of the concept on which the program is given

Files
A file is a collection of data stored on mass storage (e.g., disk or tape). The data is subdivided
into records (e.g., student information). Each record contains a number of fields (e.g., name,
USN). One (or more) field is the key field (e.g., USN). The records are organized on the mass
storage to provide convenient access for the user: sequential files, indexed files, and hashed
files.

Fig 10.1: Taxonomy of File structures

Sequential File
A sequential file is one in which records can only be one in which records can only
beaccessed one after another from beginning to end accessed one after another from
beginning to end.Figure 10.2 shows the layout of a sequential file.

Fig 10.2: Sequential file

Records are stored one after another in auxiliary storage, such as tape or disk, and there is an
EOF (end-of-file)marker after the last record. The operating system has no information about
the record addresses; it onlyknows where the whole file is stored. The only thingknown to the
operating system is that the records are sequential. Sequential files are not a convenient
organization for accessing a particular record quickly.Sequential search is even slower on
disk/tape than in main memory.

Dept. of ISE, RVCE 36


Data Structures and File Structures 16IS35

Indexed File
An index for a file is a list of key field values occurring in the file along with the address of
the corresponding record in the mass storage.Typically the key field is much smaller than the
entire record, so the index will fit in main memory. The index can be organized as a list, a
search tree, ahash table, etc. (Fig 10.3). To find a particular record:
Search the index for the desired key.
When the search returns the index entry,
extract therecords address on mass storage.
Access the mass storage at the given
address to get the desired record.

Fig 10.3: Mapping in an indexed file

Multiple indexes, one per key field, allow searches based on different fields.

Hashed Files
An alternative to storing the index as a hash table is to not have an index at all. Instead, hash
on the key to find the address of the desiredrecord and use open addressing to resolve
collisions. The usual hashing considerations arise.

Fig 10.4: Mapping in a hashed file

Dept. of ISE, RVCE 37


Data Structures and File Structures 16IS35

A hashed file uses a mathematical function to accomplish this mapping. The user gives the
key, the function maps the key to the address and passes it to theoperating system, and the
record is retrieved (Figure 10.4).
Program question

10. Implement basic operations on files

A file represents a sequence of bytes on the disk where a group of related data is stored. File
is created for permanent storage of data.In C language, we use a structure pointer of file type
to declare a file. (Student may also consider C++ language and its file functions to implement
the given program.)

The student has to use the following C functions that helps to perform basic file operations
and implement the program:
fopen( ): create a new file or open an existing file
fclose(): closes a file
getc( ): reads a character from a file
putc( ): writes a character to a file
fscanf( ): reads a set of data from a file
fprintf( ):writes a set of data to a file
getw( ):reads a integer from a file
putw( ):writes a integer to a file
fseek( ):set the position to desire point
ftell( ):gives current position in the file
rewind( ):set the position to the beginning point

Objective / purpose of the program

To implement basic operations on a file

EXPECTED OUTPUT

Must be able to createa sequential file and perform basic operations on it.

CHECK FOR ANY EXCEPTIONAL CONDITIONS

Empty file, non-existing file.

Dept. of ISE, RVCE 38


Data Structures and File Structures 16IS35

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics
TOTAL Signature
Understanding Execution Results and Conceptual Use of of the
of problem (3) Documentation Understanding appropriate (10) Faculty
(2) (2) and Design
Communication Techniques
of Concepts (1)
(2)

10

Dept. of ISE, RVCE 39


Data Structures and File Structures 16IS35

Program No. 10

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 40


Data Structures and File Structures 16IS35

Program No. 11 & 12

Details of the concept on which the program is given

Hashed Files
An alternative to storing the index as a hash table is to not have an index at all. Instead, hash
on the key to find the address of the desiredrecord and use open addressing to resolve
collisions. The usual hashing considerations arise.

Hashing methods
For key-address mapping, there are several hashing methods:
Direct hashing: In direct hashing, the key is the data file address without anyalgorithmic
manipulation. The file must therefore contain a record for every possible key. Although
situations suitablefor direct hashing are limited, it can be very powerful,because it guarantees
that there are no synonyms or collisions, as with othermethods.

Fig. 11.1: Direct hashing

Modulo division hashing: Also known as division remainder hashing, modulo division
method divides the key by the file size and uses the remainder plus 1 for the address. This
gives the simple hashing algorithm that follows, where list_size is the number of elements in
the file. The reason for adding a 1 to the mod operation result is that our list starts with 1
instead of 0.
address = key mod list_size + 1

Dept. of ISE, RVCE 41


Data Structures and File Structures 16IS35

Fig11.2: Modulo division

Digit extraction hashing: Using digit extraction hashing, selected digits are extracted from
the key and used as the address. For example, using six-digit employee number to hash to a
three-digit address(000999), we could select the first, third and fourth digits (from the left)
and use them as the address. Using thekeys from Figure 11.2, we hash them to the following
addresses:
125870 -->158 122801 -->128 121267 -->112

Collision
Generally, the population of keys for a hashed list is greater than the number of records in the
data file. For example, if we have a file of 50 students for a class in which the students are
identified by the last four digits of their social security number, then there are 200 possible
keys for each element in the file (10,000/50). Because there are many keys for each address
in the file, there is a possibility that more than one key will hash to the same address in
thefile. We call the set of keys that hash to the same address in our list synonyms. The
collision concept is illustrated in Figure 11.3.

Fig 11.3: Collision

Dept. of ISE, RVCE 42


Data Structures and File Structures 16IS35

Collision resolution: With the exception of the direct method, when we hash a new key to an
address, we may create a collision. There are several methods forhandling collisions, each of
them independent of the hashing algorithm. That is, any hashing method can be used with
any collision resolution method.
Open addressing resolution:

Linked list resolution

Bucket hashing resolution

Program question

11. Implement simple hash algorithm for files and records

Open addressing hashingcomputes a second address, or if necessary a third, or fourth, or so


on, continuing until it finds an empty spot. It is necessary that the computation of secondary
addresses eventually visits every possible storage location. Linear probing is a simple
approach in which storage locations are accessed in increasing order until an empty location
is found. It is possible, of course, for the hash table to become completely filled, in which
case an error is reported when a new item cannot be inserted.The tricky part of hashing with
open addressing is deletions, because its not possible to simply delete an item because some
other item may rely on the fact that its storage location was filled when the item was inserted.

Dept. of ISE, RVCE 43


Data Structures and File Structures 16IS35

The solution is to have two types of items in a storage location: 0 - which indicates that the
storage location has never been used; non zero content element stored in the cell (currently
occupied). Keep probing until the element is found, or the table exhausts.

ALGORITHM of the program


display contents of the hash table
Algorithm display()
fori 0 to n-1
print hashTable [ i ]
end for
end Algorithm

hash the given numbers and store them in hash table


Algorithm hashing( element )
key element % hashTableSize
if hashTable[ key ] = 0 then
store the element at hashTable[ key ]: return
else
for key key + 1 to n-1
if hashTable[ key ] = 0 then
store the element at hashTable[ key ]: return
end if
end for
for key 0 to n-1
if hashTable[ key ] = 0 then
store the element at hashTable[ key ]: return
end if
end for
end if-else
print ERROR: TABLE FULL, insertion failed
end Algorithm

delete a given number from the hash table


Algorithm deleteH( element )
key element % hashTableSize
if hashTable[ key ] = element then
hashTable[ key ] 0/* element deleted */: return
else
for key key + 1 to n-1
if hashTable[ key ] = element then
hashTable[ key ] 0/* element deleted */: return
end if
end for
for key 0 to n-1
if hashTable[ key ] = element then
hashTable[ key ] 0/* element deleted */: return
end if
end for

Dept. of ISE, RVCE 44


Data Structures and File Structures 16IS35

end if-else
print Element not found
end Algorithm

Applications of File structures: The various File structureapplications are:


Data Management
Information retrieval
Library automation
Information processing

Programs in File structures:


Implementation of Open addressing technique
Implementation of separate chaining with linked list
Implementation of B-Tree
Implementation of secondary index on set of Records

Objective / purpose of the program

To implement simple hash algorithm for files with records


Program on File structure

EXPECTED OUTPUT

Hash table must be created for file with record


Display the contents of hash table
Must be able to search a given file record using hash table display message
appropriately
Must be able delete a file record using hash table.

CHECK FOR ANY EXCEPTIONAL CONDITIONS

Hash table full/empty


Record found/not found
Record deletion success/failed

Dept. of ISE, RVCE 45


Data Structures and File Structures 16IS35

Program Marks for Execution Marks for Viva voce


No. (7) (3)
Rubrics Rubrics
Signature
Understanding Execution Results and Conceptual Use of TOTAL of the
of problem (3) Documentation Understanding appropriate (10)
(2) (2) and Design
Faculty
Communication Techniques
of Concepts (1)
(2)

11

12

Dept. of ISE, RVCE 46


Data Structures and File Structures 16IS35

Program No. 11

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 47


Data Structures and File Structures 16IS35

Program No. 12

Paste your DATA SHEET here

[Page intentionally left blank, student to paste his/her data sheet after evaluated by the staff
in-charge]

Dept. of ISE, RVCE 48


Data Structures and File Structures 16IS35

Sample Viva Questions


1. What is a data structure?
2. What are the different types of data structure?
3. What are primitive and non-primitive data structures?
4. What is a linear data structure? Give examples.
5. What is a non-linear data structure? Give examples.
6. What is a pointer? Mention some of the uses of pointers.
7. What is an array? Mention the different types of arrays.
8. What are the applications of arrays?
9. What is a stack and what are the operations performed on stacks?
10. What are the applications of stacks?
11. Where do you use postfix and prefix notations?
12. What is recursion?
13. Give difference between iterative method and recursive method
14. What are queues and what are the operations performed on them?
15. What are the different types of queues?
16. Mention the application of each type of queue?
17. What is the difference between a linear queue and circular queue?
18. What is a dequeue?
19. What are linked lists and how are they represented?
20. What are the differences between an array and a linked list. Which is better and why?
21. Mention the applications of linked lists.
22. What is a tree?
23. What are the different representations of trees in memory?
24. What are directed trees and undirected trees?
25. What do you mean by degree of a node?
26. What are indegree and outdegree of a node?
27. What do you understand by level of a node?
28. What is an ordered tree?
29. What are sub-trees?
30. What do you mean by height of a tree?
31. What is a binary tree?
32. What is a strictly binary tree?
33. What is a complete binary tree?
34. What is a almost complete binary tree?
35. What is a heap?
36. List heap properties
37. What is a forest?
38. What are the different traversals of a tree?
39. What is an expression tree?
40. What is a sparse matrix and what are the uses of it?
41. What is hashing?
42. List the applications of circular singly linked list.
43. List the applications of doubly linked list.
44. What is File Structure?
45. What is a File, field, Record?
46. What is fixed length record, Variable length record?
47. What are the different modes of opening a file?
48. What is the difference between read() and getline()?
49. Explain any one collision resolution technique.
50. What is Btree?

Dept. of ISE, RVCE 49


Data Structures and File Structures 16IS35

Basic Commands of vi
General Startup
To use vi: vi filename
To exit vi and save changes: ZZ or :wq
To exit vi without saving changes: :q!
To enter vi command mode:[esc]

Counts
A number preceding any vi command tells vi to repeat
that command that many times.

Cursor Movement
h move left (backspace)
j move down
k move up
l move right (spacebar)
[return] move to the beginning of the next line
$ last column on the current line
0 move cursor to the first column on the current line
^ move cursor to first nonblank column on the current line
w move to the beginning of the next word or
punctuation mark
W move past the next space
b move to the beginning of the previous word or
punctuation mark
B move to the beginning of the previous word,
ignores punctuation
e end of next word or punctuation mark
E end of next word, ignoring punctuation
H move cursor to the top of the screen
M move cursor to the middle of the screen
L move cursor to the bottom of the screen

Screen Movement
G move to the last line in the file
xG move to line x
z+ move current line to top of screen
z move current line to the middle of screen
z- move current line to the bottom of screen
^F move forward one screen
^B move backward one line
^D move forward one half screen
^U move backward one half screen
^R redraw screen
( does not work with VT100 type terminals )
^L redraw screen
( does not work with Televideo terminals )

Inserting
r replace character under cursor with next
character typed
R keep replacing character until [esc] is hit
i insert before cursor
a append after cursor
A append at end of line
O open line above cursor and enter append mode

Deleting
x delete character under cursor
dd delete line under cursor
dw delete word under cursor
db delete word before cursor

Dept. of ISE, RVCE 50


Data Structures and File Structures 16IS35

Copying Code
yy (yank)'copies' line which may then be put by
the p(put) command. Precede with a count for
multiple lines.

Put Command
brings back previous deletion or yank of lines,
words, or characters
P bring back before cursor
p bring back after cursor

Find Commands
? finds a word going backwards
/ finds a word going forwards
f finds a character on the line under the
cursor going forward
F finds a character on the line under the
cursor going backwards
t find a character on the current line going
forward and stop one character before it
T find a character on the current line going
backward and stop one character before it
; repeat last f, F, t, T

Miscellaneous Commands
. repeat last command
u undoes last command issued
U undoes all commands on one line
xp deletes first character and inserts after
second (swap)
J join current line with the next line
^G display current line number
% if at one parenthesis, will jump to its mate
mx mark current line with character x
'x find line marked with character x
NOTE:Marks are internal and not written to the file.

Line Editor Mode


Any commands form the line editor ex can be issued
upon entering line mode.
To enter: type ':'
To exit: press[return] or [esc]

ex Commands
For a complete list consult the UNIX Programmer's Manual

READING FILES
:r filenamecopies (reads) filename after cursor in file currently
editing

WRITE FILE
:w saves the current file without quitting

MOVING
:# move to line #
:$ move to last line of file

SHELL ESCAPE
:!'cmd' executes 'cmd' as a shell command.

Dept. of ISE, RVCE 51


Data Structures and File Structures 16IS35

Basic Commands of GDB


Startup
% gdb -help print startup help, show switches
% gdb object normal debug
% gdb object core core debug (must specify core file)
%% gdb object pid attach to running process
% gdb use file command to load object

Help
(gdb) help list command classes
(gdb) help running list commands in one command class
(gdb) help run bottom-level help for a command "run"
(gdb) help info list info commands (running program state)
(gdb) help info line help for a particular info command
(gdb) help show list show commands (gdb state)
(gdb) help show commands specific help for a show command

Breakpoints
(gdb) break main set a breakpoint on a function
(gdb) break 101 set a breakpoint on a line number
(gdb) break basic.c:101 set breakpoint at file and line (or function)
(gdb) info breakpoints show breakpoints
(gdb) delete 1 delete a breakpoint by number
(gdb) delete delete all breakpoints (prompted)
(gdb) clear delete breakpoints at current line
(gdb) clear function delete breakpoints at function
(gdb) clear line delete breakpoints at line
(gdb) disable 2 turn a breakpoint off, but don't remove it
(gdb) enable 2 turn disabled breakpoint back on
(gdb) tbreak function|line set a temporary breakpoint
(gdb) commands break-no ... end set gdb commands with breakpoint
(gdb) ignore break-no count ignore bpt N-1 times before activation
(gdb) condition break-no expression break only if condition is true
(gdb) condition 2 i == 20 example: break on breakpoint 2 if i equals 20
(gdb) watch expression set software watchpoint on variable
(gdb) info watchpoints show current watchpoints

Running the program


(gdb) run run the program with current arguments
(gdb) run args redirectionrun with args and redirection
(gdb) set args args... set arguments for run
(gdb) show args show current arguments to run
(gdb) cont continue the program
(gdb) step single step the program; step into functions
(gdb) step count singlestep \fIcount\fR times
(gdb) next step but step over functions
(gdb) next count next \fIcount\fR times
(gdb) CTRL-C actually SIGINT, stop execution of current program
(gdb) attach process-id attach to running program
(gdb) detach detach from running program
(gdb) finish finish current function's execution
(gdb) kill kill current executing program

Stack backtrace
(gdb) bt print stack backtrace
(gdb) frame show current execution position
(gdb) up move up stack trace (towards main)
(gdb) down move down stack trace (away from main)
(gdb) info locals print automatic variables in frame
(gdb) info args print function parameters

Dept. of ISE, RVCE 52


Data Structures and File Structures 16IS35

Browsing source
(gdb) list 101 list 10 lines around line 101
(gdb) list 1,10 list lines 1 to 10
(gdb) list main list lines around function
(gdb) list basic.c:main list from another file basic.c
(gdb) list - list previous 10 lines
(gdb) list *0x22e4 list source at address
(gdb) cd dir change current directory to \fIdir\fR
(gdb) pwd print working directory
(gdb) search regexpr forward current for regular expression
(gdb) reverse-search regexpr backward search for regular expression
(gdb) dir dirname add directory to source path
(gdb) dir reset source path to nothing
(gdb) show directories show source path

Browsing Data
(gdb) print expression print expression, added to value history
(gdb) print/x expressionR print in hex
(gdb) print array[i]@count artificial array - print array range
(gdb) print $ print last value
(gdb) print *$->next print thru list
(gdb) print $1 print value 1 from value history
(gdb) print ::gx force scope to be global
(gdb) print 'basic.c'::gx global scope in named file (>=4.6)
(gdb) print/x &main print address of function
(gdb) x/countFormatSize address low-level examine command
(gdb) x/x &gx print gx in hex
(gdb) x/4wx &main print 4 longs at start of \fImain\fR in hex
(gdb) x/gf &gd1 print double
(gdb) help x show formats for x
(gdb) info locals print local automatics only
(gdb) info functions regexp print function names
(gdb) info variables regexp print global variable names
(gdb) ptype name print type definition
(gdb) whatis expression print type of expression
(gdb) set variable = expression assign value
(gdb) display expression display expression result at stop
(gdb) undisplay delete displays
(gdb) info display show displays
(gdb) show values print value history (>= gdb 4.0)
(gdb) info history print value history (gdb 3.5)

Object File manipulation


(gdb) file object load new file for debug (sym+exec)
(gdb) file discard sym+exec file info
(gdb) symbol-file object load only symbol table
(gdb) exec-file object specify object to run (not sym-file)
(gdb) core-file core post-mortem debugging

Signal Control
(gdb) info signals print signal setup
(gdb) handle signo actions set debugger actions for signal
(gdb) handle INT print print message when signal occurs
(gdb) handle INT noprint don't print message
(gdb) handle INT stop stop program when signal occurs
(gdb) handle INT nostop don't stop program
(gdb) handle INT pass allow program to receive signal
(gdb) handle INT nopass debugger catches signal; program doesn't
(gdb) signal signo continue and send signal to program
(gdb) signal 0 continue and send no signal to program

Machine-level Debug

Dept. of ISE, RVCE 53


Data Structures and File Structures 16IS35

(gdb) info registers print registers sans floats


(gdb) info all-registers print all registers
(gdb) print/x $pc print one register
(gdb) stepi single step at machine level
(gdb) si single step at machine level
(gdb) nexti single step (over functions) at machine level
(gdb) ni single step (over functions) at machine level
(gdb) display/i $pc print current instruction in display
(gdb) x/x &gx print variable gx in hex
(gdb) info line 22 print addresses for object code for line 22
(gdb) info line *0x2c4e print line number of object code at address
(gdb) x/10i main disassemble first 10 instructions in \fImain\fR
(gdb) disassemble addr dissassemble code for function around addr

History Display
(gdb) show commands print command history (>= gdb 4.0)
(gdb) info editing print command history (gdb 3.5)
(gdb) ESC-CTRL-J switch to vi edit mode from emacs edit mode
(gdb) set history expansion on turn on c-shell like history
(gdb) break class::member set breakpoint on class member. may get menu
(gdb) list class::member list member in class
(gdb) ptype class print class members
(gdb) print *this print contents of this pointer
(gdb) rbreak regexpr useful for breakpoint on overloaded member name

Miscellaneous
(gdb) define command ... end define user command
(gdb) RETURN repeat last command
(gdb) shell command args execute shell command
(gdb) source file load gdb commands from file
(gdb) quit quit gdb

Dept. of ISE, RVCE 54

You might also like