0% found this document useful (0 votes)
3 views108 pages

DSA Ashish Aaher 01

The document outlines practical exercises for a Data Structures and Algorithms course, focusing on implementing a telephone book database using hash tables and collision handling techniques. It includes code examples for inserting, searching, displaying, and deleting telephone numbers, as well as implementing a dictionary ADT using hashing. Additionally, it describes constructing a tree structure for organizing chapters and sections in a book.

Uploaded by

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

DSA Ashish Aaher 01

The document outlines practical exercises for a Data Structures and Algorithms course, focusing on implementing a telephone book database using hash tables and collision handling techniques. It includes code examples for inserting, searching, displaying, and deleting telephone numbers, as well as implementing a dictionary ADT using hashing. Additionally, it describes constructing a tree structure for organizing chapters and sections in a book.

Uploaded by

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

DSA Practicals

Name : Aher Ashish Vinod

Roll no: 01

Seat Number : S400470810

Subject : Data structures and Algorithm


Name : Aher Ashish Vinod ; Roll no: 01 ; Seat Number : S40001080101

Prac cal No.1


Consider telephone book database of N clients.

Make use of a hash table implementa on to


quickly look up client ‘s telephone number. Make
use of two collision handling techniques and

compare them using number of comparisons

required to find a set of telephone numbers

#include <iostream> using

namespace std;

struct Node

{ int value;

Node* next;

Node(int v) : value(v), next(nullptr) {}

};

class Hashing { sta c const int TABLE_SIZE

= 10;

Node* table[TABLE_SIZE];
int hashFunc on(int value) { return

value % TABLE_SIZE;

public:

Hashing() { for (int i = 0; i < TABLE_SIZE;


i++) table[i]

= nullptr;

void insertElement(int value) { int

idx = hashFunc on(value); Node*

newNode = new Node(value);

if (!table[idx])

{ table[idx] =

newNode;

} else { Node*

curr = table[idx]; while

(curr->next) curr =

curr->next; curr->next

= newNode;

cout << "Inserted " << value << " at index " << idx << endl;

void display() { for (int i = 0; i


< TABLE_SIZE; i++) { cout
<< "a[" << i << "] :"; Node*
curr = table[i]; while (curr)
{ cout << " -> " <<
curr->value; curr =
curr->next;

cout << "\n";

int searchElement(int value) { int idx = hashFunc on(value);

Node* curr = table[idx]; while (curr) { if (curr->value ==

value) { cout <<

"Element " << value << " found at index " << idx << endl;

return idx;

} curr =

curr->next;

cout << "Element " << value << " not found\n";

return -1;

void deleteElement(int value) {

int idx = hashFunc on(value);

Node* curr = table[idx];


Node* prev = nullptr; while (curr

&& curr->value != value) {


prev = curr;

curr = curr->next;

} if (!curr) { cout << "Element " << value << " not

found, cannot delete\n";

return; } if

(!prev) { table[idx] =

curr->next; } else

{ prev->next =

curr->next;

} delete curr; cout << "Deleted " << value << "

from index " << idx << endl;

};

int main() {
Hashing h; int choice,

num;

do { cout << "\nTelephone Book

Menu:\n"

<< "1. Insert\n"

<< "2. Display\n"

<< "3. Search\n"

<< "4. Delete\n"


<< "5. Exit\n"
<< "Choice: "; cin

>> choice;
switch (choice)

{ case 1:

cout << "Enter phone no. to be inserted: ";

cin >> num;

h.insertElement(num);

break; case 2:

h.display(); break;
case

3: cout << "Enter the no to be searched:

"; cin >> num;

h.searchElement(num);
break; case 4: cout <<

"Enter the phno. to be deleted: "; cin >>

num;

h.deleteElement(num);
break; case

5:

cout << "Exi ng...\n";

break; default: cout <<

"Invalid choice. Try again.\n";

} while (choice != 5);

return 0;
}

Output :

Telephone Book Menu:

1. Insert

2. Display

3. Search

4. Delete 5. Exit

Choice: 1

Enter phone no. to be inserted: 98701543210

Inserted 98701543210 at index 0

Telephone Book Menu:

1. Insert

2. Display

3. Search

4. Delete 5. Exit

Choice: 1

Enter phone no. to be inserted: 12345017891


Inserted 12345017891 at index 1

Telephone Book Menu:

1. Insert

2. Display

3. Search 4. Delete

5. Exit

Choice: 1

Enter phone no. to be inserted: 5555555555

Inserted 5555555555 at index 5

Telephone Book Menu:

1. Insert

2. Display

3. Search

4. Delete

5. Exit Choice: 2 a[0] : -> 98701543210 a[1] : -> 12345017891 a[2] : a[3] : a[4] : a[5] : ->

5555555555

a[01] :

a[7] :

a[8] :

a[9] :

Telephone Book Menu:

1. Insert

2. Display
3. Search

4. Delete

5. Exit

Choice: 3

Enter the no to be searched: 12345017891

Element 12345017891 found at index 1

Telephone Book Menu:

1. Insert

2. Display

3. Search

4. Delete 5. Exit

Choice: 4

Enter the phno. to be deleted: 98701543210

Deleted 98701543210 from index 0

Telephone Book Menu:

1. Insert

2. Display

3. Search

4. Delete 5. Exit Choice: 2 a[0] : a[1] : ->

12345017891
a[2] : a[3] : a[4] :

a[5] : -> 5555555555

a[01] :

a[7] :

a[8] :

a[9] :
Telephone Book Menu:

1. Insert

2. Display

3. Search

4. Delete 5. Exit

Choice: 5 Exi

ng...
Name : Aher Ashish Vinod ; Roll no: 01 ; Seat Number : S40001080101

Practical No 2:
Implement all the functions of a dictionary (ADT)
using hashing and handle collisions using
chaining with / without replacement. Data: Set of
(key, value) pairs, Keys are mapped to values,
Keys must be comparable, Keys must be unique
Standard Opera ons: Insert (key, value),

Find(key), Delete(key)

#include<iostream>

#include<string.h>

#include<iostream>

#include<string.h>

using namespace std;

class HashFunc on

{ typedef struct

hash

{ long key;

char name[10];
} hash;

hash h[10];

public:

HashFunc on();

void insert(); void


display(); int
find(long); void
Delete(long);
};

HashFunc on::HashFunc on()


{ int i; for(i = 0; i

< 10; i++)

{ h[i].key = -1;

strcpy(h[i].name, "NULL");

void HashFunc on::Delete(long k)

{ int index =

find(k); if(index

== -1)

cout << "\n\tkey Not Found";


} else

{ h[index].key = -1;

strcpy(h[index].name, "NULL");

cout << "\n\tkey is Deleted";

int HashFunc on::find(long k)


{ int i; for(i = 0; i

< 10; i++)

{ if(h[i].key

== k)

{
cout << "\n\t" << h[i].key << " is Found at " << i << " Loca on with name " <<
h[i].name;

return i;

return -1; // Ensure to return -1 if the key is not found

void HashFunc on::display()


{ int

i;

cout << "\n\t\tkey\t\tName";

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


{

cout << "\n\th[" << i << "]\t" << h[i].key << "\t\t" << h[i].name;

void HashFunc on::insert()

char ans, n[10],

ntemp[10]; long k, temp;

int hi, cnt = 0, flag = 0, i;

do

{ if(cnt >=

10)

cout << "\n\tHash Table is FULL";

break;

cout << "\n\tEnter a Telephone NO:";

cin >> k; cout << "\n\tEnter a client

Name:"; cin >> n;

hi = k % 10; //hash func on

if(h[hi].key == -1)

{ h[hi].key =
k;

strcpy(h[hi].name, n);

else

{ if(h[hi].key %

10 != hi)

{ temp =

h[hi].key;

strcpy(ntemp, h[hi].name);

h[hi].key = k;

strcpy(h[hi].name, n); for(i

= hi + 1; i < 10; i++)

{ if(h[i].key ==

-1)

{ h[i].key =

temp;

strcpy(h[i].name, ntemp);

flag = 1; break;

for(i = 0; i < hi && flag == 0; i++)


{ if(h[i].key ==

-1)

{ h[i].key =

temp;

strcpy(h[i].name, ntemp);

break;

}
} } else

{ for(i = hi + 1; i < 10;

i++)

{ if(h[i].key ==

-1)

h[i].key = k; strcpy(h[i].name,

n);

flag = 1; break;

for(i = 0; i < hi && flag == 0; i++)

{ if(h[i].key ==

-1)
{ h[i].key =

k;

strcpy(h[i].name, n);

break;

} flag = 0; cnt++; cout <<

"\n\t.....Do you want to insert more key: y/n"; cin >>

ans;

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

int main()

long k; int

ch, index; char

ans;

HashFunc on obj;

do

{
cout << "\n\t***Telephone(ADT)*****"; cout <<
"\n\t1.insert\n\t2.Display\n\t3.Find\n\t4.Delete\n\t5.Exit"; cout <<

"\n\t....Enter your choice:";

cin >> ch;


switch(ch)

{ case
1:
obj.insert();
break; case 2:
obj.display(); break;

case 3:

cout << "\n\tEnter a key which you want to search:";


cin >> k; index

= obj.find(k); if(index

== -1)

cout << "\n\tkey Not found";

break; case

4:

cout << "\n\tEnter a key which you want to delete:";


cin >> k;
obj.Delete(k); break;
case 5:

break;

cout << "\n\t.... Do you want to con nue in main menu: y/n";

cin >> ans;


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

//out put

/*

***Telephone(ADT)*****

1.insert

2.Display

3.Find

4.Delete

5.Exit

....Enter your choice:1

Enter a Telephone NO:45014501

Enter a client Name:ayush

.....Do you want to insert more key: y/ny

Enter a Telephone NO:01015783401

Enter a client Name:tushar

.....Do you want to insert more key: y/ny


Enter a Telephone NO:50174587014

Enter a client Name:toshal

.....Do you want to insert more key: y/ny

Enter a Telephone NO:874015780157

Enter a client Name:dinesh

.....Do you want to insert more key: y/nn

.... Do you want to con nue in main menu: y/ny

***Telephone(ADT)*****

1.insert

2.Display

3.Find

4.Delete

5.Exit

....Enter your choice:2

key Name h[0] -1

NULL h[1] -1 NULL

h[2] -1 NULL h[3] -


1 NULL h[4]

50174587014 toshal
h[5] -1 NULL h[01]
45014501 ayush h[7]
874015780157 dinesh h[8]
01015783401 tushar h[9]

-1 NULL

.... Do you want to con nue in main menu: y/n

*/

Name : Aher Ashish Vinod ; Roll no: 01 ; Seat Number : S40001080101

Practical No:3

A book consists of chapters, chapters consist of sec

ons and sec ons consist of subsec ons.

Construct a tree and print the nodes. Find the me and

space requirements of your method.


#include<iostream>
#include<stdlib.h>

#include<string.h> using

namespace std;

struct node { char

name[20]; node*

next; node*

down;

int flag;

};

class Gll { char

ch[20];

int n, i;

node* head = NULL, * temp = NULL, * t1 = NULL, * t2 = NULL;

public: node*
create(); void
insertb(); void
insertc(); void
inserts(); void
insertss(); void
displayb();
};
node* Gll::create() { node*
p = new(node); p->next =
NULL; p-

>down = NULL;

p->flag = 0; cout <<

"\nEnter the name: "; cin >>

p->name;

return p;

void Gll::insertb() { if
(head == NULL)

{ t1 =

create();

head = t1;

} else { cout << "\nBook

already exists.";

void Gll::insertc() { if (head ==

NULL) { cout << "\nThere is

no book.";

else { cout << "\nHow many chapters do you want to

insert? ";

cin >> n; for (i =


0; i < n; i++) { t1 =
create(); if

(head->flag == 0)
head->down = t1;

head->flag = 1;

void Gll::inserts() { if (head ==

NULL) { cout << "\nThere is

no book.";

} else { cout << "\nEnter the name of the chapter on which you want to enter

the sec on: "; cin >> ch; temp = head; if (temp->flag == 0) { cout

<< "\nThere are no chapters in the book.";

} else { temp = temp->down; while

(temp != NULL) { if (!strcmp(ch, temp>name))

{ cout << "\nHow many sec ons do you want to

enter? ";

cin >> n; for


(i = 0; i < n; i++) { t1
= create(); if
(temp->flag == 0)
{ temp->down = t1;
temp->flag = 1;

t2 = temp->down;
} else

{ while

(t2->next !=

NULL) { t2 = t2-

>next;

t2->next = t1;

break;

temp = temp->next;

void Gll::insertss() { if (head


== NULL) { cout << "\nThere is no book."; } else { cout <<

"\nEnter the name of chapter on which you want to enter the sec on: "; cin >>

ch; temp = head; if (temp->flag == 0) { cout

<< "\nThere are no chapters in the book.";

} else { temp =

temp->down; while (temp !=


NULL) { if (!strcmp(ch,

temp->name)) {

cout << "\nEnter the name of the sec on in which you want to enter the
subsec on: ";
cin >> ch; if (temp->flag

== 0) { cout << "\nThere are no

sec ons.";

} else

{ t2 = temp->down;

while (t2 != NULL) { if

(!strcmp(ch, t2->name)) { cout << "\nHow many subsec

ons do you want to enter? ";

cin >> n;
for (i = 0; i < n; i++)
{ t1 = create();
if (t2->flag == 0)
{ t2->down = t1;

t2->flag = 1;

else

while (t2->next !=

NULL) { t2 = t2-

>next;

t2->next = t1;

}
} break;

t2 = t2->next;

temp = temp->next;

void Gll::displayb() { if (head ==


NULL) { cout << "\nBook does not exist."; }

else { temp = head; cout << "\nNAME OF

BOOK: " << temp->name;

if (temp->flag == 1) {

temp = temp->down; while


(temp != NULL) { cout <<

"\n\t\tNAME OF

CHAPTER: " << temp-

>name;

t1 = temp; if
(t1->flag == 1) { t1
= t1->down;
while (t1 != NULL) { cout << "\n\t\t\t\tNAME OF

SECTION: " << t1->name;

t2 = t1; if (t2->flag == 1) { t2 =

t2->down; while (t2 != NULL) { cout <<

"\n\t\t\t\t\t\tNAME OF SUBSECTION: " << t2->name;

t2 = t2->next;

} t1 =

t1->next;

temp = temp->next;

int main() {
Gll g; int

x; while

(1)

{ cout

<< "\n\nEnter

your choice:

"; cout

<< "\n1.

Insert book";
cout << "\n2.

Insert

chapter";

cout << "\n3.

Insert sec

on";

cout << "\n4.

Insert subsec

on";

cout << "\n5.

Display

book";

cout <<

"\n01. Exit";

cin >> x;

switch (x)

{ case 1:

g.insertb(); break;
case

2:

g.insertc(); break;
case

3:
g.inserts(); break;
case

4:

g.insertss(); break;
case

5:

g.displayb(); break;
case

01: exit(0);

} return

0;

/*Enter your choice:

1. Insert book

2. Insert chapter

3. Insert sec on

4. Insert subsec on

5. Display book

6. Exit1

Enter the name: data_structure

Enter your choice:

1. Insert book
2. Insert chapter

3. Insert sec on

4. Insert subsec on

5. Display book

6. Exit2

How many chapters do you want to insert? 3

Enter the name: hashing

Enter the name: collision

Enter the name: tree

Enter your choice:

1. Insert book

2. Insert chapter

3. Insert sec on

4. Insert subsec on

5. Display book

6. Exit3

Enter the name of the chapter on which you want to enter the sec on: hashing

How many sec ons do you want to enter? 2

Enter the name: open_hashing


Enter the name: hash_func on

Enter your choice:

1. Insert book

2. Insert chapter

3. Insert sec on

4. Insert subsec on

5. Display book

6. Exit4

Enter the name of chapter on which you want to enter the sec on: hashing

Enter the name of the sec on in which you want to enter the subsec on: hash_table

Enter your choice:

1. Insert book

2. Insert chapter

3. Insert sec on

4. Insert subsec on

5. Display book

6. Exit5

NAME OF BOOK: data_structure

NAME OF CHAPTER: hashing

NAME OF SECTION: open_hashing

NAME OF SECTION: hash_func on


Enter your choice:

1. Insert book

2. Insert chapter

3. Insert sec on

4. Insert subsec on

5. Display book

6. Exit01

*/

Name : Aher Ashish Vinod ; Roll no: 01 ; Seat Number : S40001080101

Prac cal No: 4


Beginning with an empty binary search tree,

construct binary search tree by inser ng the values

in the order given. A er construc ng a binary tree

i. Insert new node ii. Find number of nodes in


longest path from root iii. Minimum data value

found in the tree iv. Change a tree so that the roles

of the le and right pointers are swapped at every

node

v. Search a value

#include<iostream>

#include<cstdlib> using

namespace std;

class node

{ public:

int info;

node* le ;

node* right; };

class BST {
public: node*

root;
BST() { root

= NULL;

void insert(node*, node*);


void display(node*, int); int
min(node*); int
height(node*); void
mirror(node*); void
preorder(node*); void
inorder(node*); void
postorder(node*); void
search(node*, int);

};

int main() { int choice, num; BST

bst; node* temp; while (1)

{ cout << "--------------

---------" << endl; cout << "Opera ons on BST" << endl; cout << "---------------

--------" << endl; cout << "1. Insert Element" << endl; cout << "2. Display" <<

endl; cout << "3. Min value" << endl; cout << "4. Height" << endl; cout <<

"5. Mirror of node" << endl; cout << "01. Preorder" << endl; cout << "7.

Inorder" << endl; cout << "8. Postorder" << endl; cout << "9. No. of nodes in

longest path" << endl; cout << "10. Search an element" << endl; cout << "11.

Quit" << endl; cout << "Enter the choice: "; cin >> choice;

switch (choice)

{ case 1:
temp = new node(); cout << "Enter

the number to be inserted: "; cin >>

temp->info; bst.insert(bst.root, temp);

break;

case

2:

cout << "Display: ";

bst.display(bst.root, 1); cout

<< endl; break;

case

3:

cout << "Min value of tree: " << bst.min(bst.root) << endl;

break;

case

4:

cout << "Height of tree = " << bst.height(bst.root) << endl;

break;

case

5:

cout << "Mirror: ";

bst.mirror(bst.root); bst.display(bst.root,

1);

break;

case 01: cout <<

"Preorder Binary Tree:

"; bst.preorder(bst.root); cout

<< endl; break;


case 7: cout <<

"Inorder Binary Tree:

"; bst.inorder(bst.root); cout

<< endl; break;

case 8: cout <<

"Postorder Binary Tree: ";

bst.postorder(bst.root); cout <<

endl;

break;

case

9:

cout << "No.

of nodes in

longest path

from root is: "

<<

bst.height(bst.

root) <<

endl;

break;

case

10:

int searchdata; cout << "Enter the

element to be searched: "; cin >>

searchdata;

bst.search(bst.root, searchdata);

break;
case
11:

exit(1);

default:

cout << "Wrong choice" << endl;

// Insert func on void BST::insert(node* tree, node*

newnode) {

if (root == NULL) { root = newnode;


root->le = NULL; root->right = NULL;
cout << "Root

Node is Added" << endl; return;

}
if (tree->info == newnode->info) { cout <<

"Element already in the tree" << endl;

return;

}
if (tree->info > newnode->info)

{ if (tree->le != NULL)

{ insert(tree->le , newnode);

} else { tree->le
= newnode; tree->le
->le = NULL;
->right =
tree->le NULL;
cout << "Node added to le " << endl;
} } else { if (tree->right !=

NULL) { insert(tree->right,

newnode);

} else { tree->right = newnode;

tree>right->le = NULL;

tree->right->right = NULL; cout <<


"Node added to right" << endl;

// Display func on void

BST::display(node* ptr, int level)

{ if (ptr != NULL)

{ display(ptr->right, level + 1);

for (int i = 0; i < level; i++)

{ cout << " ";

cout << ptr->info << endl;

display(ptr->le , level + 1);

}
// Min value func on int BST::min(node* root) { if (root

== NULL) { cout << "Tree is empty" << endl;

return -1; // Return a default value indica ng tree is empty

} else {

node* temp = root;

while (temp->le != NULL) { temp

= temp->le ;

return temp->info;

// Height func on int

BST::height(node* root)

{ if (root == NULL) {

return 0;

}
int le Height = height(root->le ); int rightHeight = height(root->right);
return (le Height > rightHeight ? le

Height : rightHeight) + 1;

// Mirror func on void

BST::mirror(node* root) { if

(root != NULL) { node* temp =

root->le ; root->le = root->right;

root>right = temp;
mirror(root->le );

mirror(root->right);

// Preorder traversal func on void

BST::preorder(node* ptr) { if

(ptr != NULL) { cout

<< ptr->info << "\t";

preorder(ptr->le );

preorder(ptr->right);

// Inorder traversal func on void

BST::inorder(node* ptr) { if

(ptr != NULL) {

inorder(ptr->le ); cout <<

ptr->info << "\t";

inorder(ptr->right);

// Postorder traversal func on void

BST::postorder(node* ptr) { if

(ptr != NULL)

{ postorder(ptr->le );
postorder(ptr->right); cout

<< ptr->info << "\t";

// Search func on void BST::search(node*

ptr, int searchdata) { if (ptr == NULL)

{ cout <<

"Element not found..." << endl;

return;

} if (ptr->info == searchdata)

{ cout << "Element Found..."


<< endl; } else if (ptr->info <

searchdata) { search(ptr->right,

searchdata);

} else { search(ptr->le ,

searchdata);

/*Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder
7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 1

Enter the number to be inserted: 5019015327

Root Node is Added

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 1

Enter the number to be inserted: 4354

Node added to le

-----------------------
Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 1

Enter the number to be inserted: 39501

Node added to le

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder
8. Postorder

9. No. of nodes in longest path

10. Search an element 11. Quit

Enter the choice: 1

Enter the number to be inserted: 9843

Node added to right

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 2

Display: 5019015327

9843

4354

39501
-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 3

Min value of tree: 39501

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder
8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 4

Height of tree = 3 -----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 5

Mirror: 39501

4354

9843

5019015327 ---------------------

--

Opera ons on BST


-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 01

Preorder Binary Tree: 5019015327 4354 9843 39501

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path


10. Search an element

11. Quit

Enter the choice: 7

Inorder Binary Tree: 5019015327 9843 4354 39501

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 8

Postorder Binary Tree: 9843 39501 4354 5019015327

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value
4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element 11. Quit

Enter the choice: 9

No. of nodes in longest path from root is: 3

-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Enter the choice: 10

Enter the element to be searched: 11 Element

not found...
-----------------------

Opera ons on BST

-----------------------

1. Insert Element

2. Display

3. Min value

4. Height

5. Mirror of node

6. Preorder

7. Inorder

8. Postorder

9. No. of nodes in longest path

10. Search an element

11. Quit

Name : Aher Ashish Vinod ; Roll no: 01 ; Seat Number : S40001080101

Prac cal No : 5
Construct an expression tree from the given prefix
expression eg. +--a*bc/def and traverse it
DEPARTMENT OF Ar ficial Intelligence and
Data using postorder traversal(non recursive) and
then delete the en re tree

#include<iostream>

#include<stack>

#include<string>
using namespace std;

struct

Node{ char

data;

Node* le ;

Node* right;

};

Node* newNode(char
data){ Node* node = new
Node; node->data = data;
node>le = NULL;
node->right

= NULL; return node;

Node* constructExpressionTree(string prefix){ stack<Node*>

s;

int len = prefix.length(); for(int

i = len - 1; i >= 0; i--){ char ch

= prefix[i]; if(isdigit(ch) ||

isalpha(ch)){

s.push(newNode(ch));

} else {
Node* node = newNode(ch);

node->le = s.top();

s.pop();

node->right = s.top();

s.pop();

s.push(node);

} }

return s.top();

void postorderTraversal(Node*

root){ if(root == NULL) return;

stack<Node*> s;

s.push(root); Node* prev = NULL; while(!s.empty()){


Node* curr = s.top(); if(prev == NULL || prev->le == curr

|| prev->right ==

curr){ if(curr->le ){

s.push(curr->le );

} else if(curr->right){

s.push(curr->right);

} else if(curr->le ==

prev){ if(curr->right){

s.push(curr->right);

} else { cout <<

curr->data << " ";


s.pop(); }

prev = curr;

cout << endl;

void deleteTree(Node*

root){ if(root == NULL) return;

stack<Node*> s;

s.push(root); Node* prev = NULL; while(!s.empty()){


Node* curr = s.top(); if(prev == NULL || prev->le == curr

|| prev->right ==

curr){ if(curr->le ){

s.push(curr->le );

} else if(curr->right){

s.push(curr->right); }

} else { delete curr;

s.pop(); }

prev = curr;

int main(){ string prefix = "+--a*bc/def"; Node*


root = constructExpressionTree(prefix); cout <<
"Postorder Traversal: "; postorderTraversal(root);
deleteTree(root); return 0;
}

/*student@ioe-aids-151:~$ ./a.out

Postorder Traversal: a b c * - d e / - f +

*/

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal No:01


There are flight paths between ci es. If there is a flight between city A and city B then there
is an edge between the ci es. The cost of the edge can be the me that flight take to reach
city B from A, or the amount of fuel used for the journey. Represent this as a graph. The
node can be represented by airport name or name of the city. Use adjacency list representa
on of the graph or use adjacency matrix representa on of the graph. Check whether the
graph is connected or not. Jus fy the storage representa on used.
#include<iostream>

#include<string.h> using

namespace std;

class flight { public: int am[10][10]; //

matrix array for weight char

city_index[10][10]; // array for City

name flight(); //constructor of class int

create(); void display(int city_count);

};

flight::flight() //ini alizing matrix

{ int

i,j;

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

{ strcpy(city_index[i],"xx");

} for(i=0;i<10;i++)

{ for(j=0;j<10;j++)

{ am[i][j]=0;

int flight::create()
{ int

city_count=0,j,si,di,wt;

char s[10],d[10],c; do

{ cout<<"\n\tEnter Source
City : ";

cin>>s; cout<<"\n\tEnter Des na

on City : ";

cin>>d; for(j=0;j<10;j++)

{ if(strcmp(city_index[j],s)==0) //if source is already available then

break

break; //if both strings are equal then break the

condi on

} if(j==10) { strcpy(city_index[city_count],s); // If not

presesnt then copy that

source city at current index ini ally it is 0

city_count++;

for(j=0;j<10;j++)

if(strcmp(city_index[j],d)==0)

break; }
if(j==10) // same for des na on

{ strcpy(city_index[city_count],d);

city_count++;

cout<<"\n\t Enter Distance From "<<s<<" And "<<d<<": "; cin>>wt;

for(j=0;j<10;j++)

if(strcmp(city_index[j],s)==0) si=j;

if(strcmp(city_index[j],d)==0) di=j;

am[si][di]=wt; cout<<"\n\t Do you want to add more

ci es.....(y/n) : "; cin>>c; }while(c=='y'||c=='Y');

return(city_count);

} void flight::display(int city_count) // 4*4 matrix it will return 4 as city

count

{ int i,j;

cout<<"\n\t Displaying Adjacency Matrix :\n\t";

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

cout<<"\t"<<city_index[i]; cout<<"\n";

for(i=0;i<city_count;i++)
{ cout<<"\t"<<city_index[i]; for(j=0;j<city_count;j++) //
j is

for Row i is for incremeanta on {

cout<<"\t"<<am[i][j];

} cout<<"\n";

int main()

{ flight f; int

n,city_count;

char c;

do

cout<<"\n\t*** Flight Main Menu *****";

cout<<"\n\t1. Create \n\t2. Adjacency Matrix\n\t3. Exit"; cout<<"\n\t.....Enter

your choice : "; cin>>n; switch(n)

case 1:

city_count=f.create(); break;

case 2:

f.display(city_count); break;
case 3:

return 0;
} cout<<"\n\t Do you Want to Con nue in Main

Menu....(y/n) : "; cin>>c; }while(c=='y'||c=='Y'); return 0;

*** Flight Main Menu *****

1. Create

2. Adjacency Matrix

3. Exit

.....Enter your choice : 1

Enter Source City : A

Enter Des na on City : B

Enter Distance From A And B: 100

Do you want to add more ci es.....(y/n) : y

Enter Source City : B

Enter Des na on City : C

Enter Distance From B And C: 200

Do you want to add more ci es.....(y/n) : y

Enter Source City : A

Enter Des na on City : D


Enter Distance From A And D: 300

Do you want to add more ci es.....(y/n) : n

Do you Want to Con nue in Main Menu....(y/n) : y

*** Flight Main Menu *****

1. Create

2. Adjacency Matrix

3. Exit

.....Enter your choice : 2

Displaying Adjacency Matrix :

A B C D

A 0 100 0 300

B 0 0 200 0

C 0 0 0 0 D0 0 0 0

Do you Want to Con nue in Main Menu....(y/n) : n

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal No:7


You have a business with several offices; you
want to lease phone lines to connect them up with
each other; and the phone company charges
different amounts of money to connect different

pairs of ci es. You want a set of lines that

connects all your offices with a minimum total


cost. Solve the problem by sugges ng appropriate

data structures

#include<iostream> using

namespace std;

class tree { int a[20][20], l, u, w, i, j, v,

e, visited[20];

public:

void input();

void display();

void

minimum();

};

void tree::input()

{ cout << "Enter the number of

branches: "; cin >> v;

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

{ visited[i] =
0;

for(j = 0; j < v; j++)


{

a[i][j] = 999; // Ini alizing all matrix values to a large number

cout << "\nEnter the number of connec ons: ";

cin >> e;

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

cout << "Enter the end branches of connec ons (l, u): ";

cin >> l >> u; cout << "Enter the phone company charges for

this connec on: "; cin >> w; a[l-1][u-1] = a[u-1][l-1] = w;

// Set the weight for both direc ons

void tree::display()

{ cout << "\nAdjacency

matrix:\n"; for(i = 0; i < v; i++)

{ for(j = 0; j < v;

j++)

{ cout <<

a[i][j] << " ";

} cout

<< endl;
}

void tree::minimum()

{ int p = 0, q = 0, total = 0,
min;

visited[0] = 1; // Start from the first branch

for(int count = 0; count < (v-1); count++) // Loop un l we have included (v-1) edges

{ min =

999;

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

if(visited[i] == 1) // Look for visited nodes

{ for(j = 0;

j < v; j++)

if(visited[j] != 1 && a[i][j] != 999) // Find the minimum edge connec ng a


visited node

{ if(min >

a[i][j])

{ min =

a[i][j]; p = i;

q
= j;

visited[q] = 1; // Mark the new node as visited

total += min; // Add the minimum edge cost to the total

cout << "Minimum cost connec on is: " << (p+1) << " -> " << (q+1) << " with charge:
" << min << endl;

cout << "The minimum total cost of connec ons of all branches is: " << total << endl; }

int main()
{ int
ch; tree
t;

do

{
cout << "Prim's Algorithm\n"; cout << "\n1.
Input\n2. Display\n3. Minimum\n4. Exit\n"; cout <<

"Enter your choice: ";

cin >> ch;

switch(ch)
{ case

1:

cout << "Input your values\n";


t.input(); break;
case

2:

cout << "Display the contents\n";

t.display(); break;
case

3:

cout << "Minimum\n";

t.minimum();

break; case 4:

cout << "Exi ng...\n"; break;

default: cout << "Invalid choice! Please try

again.\n";

} while(ch != 4);

return 0;

/* output

Prim's Algorithm
1. Input

2. Display

3. Minimum

4. Exit

Enter your choice: 1

Input your values

Enter the number of branches: 4

Enter the number of connec ons: 5

Enter the end branches of connec ons (l, u): 1

Enter the phone company charges for this connec on: 101

Enter the end branches of connec ons (l, u): 1

Enter the phone company charges for this connec on: 200

Enter the end branches of connec ons (l, u): 3

Enter the phone company charges for this connec on: 201

Enter the end branches of connec ons (l, u): 2

Enter the phone company charges for this connec on: 300

Enter the end branches of connec ons (l, u): 1

Enter the phone company charges for this connec on: 301

Prim's Algorithm
1. Input

2. Display

3. Minimum

4. Exit

Enter your choice: 2

Display the contents

Adjacency matrix:

999 101 200 301

101 999 999 300

200 999 999 201

301 300 201 999

Prim's Algorithm

1. Input

2. Display

3. Minimum

4. Exit

Enter your choice: 3

Minimum

Minimum cost connec on is: 1 -> 2 with charge: 101

Minimum cost connec on is: 1 -> 3 with charge: 200

Minimum cost connec on is: 3 -> 4 with charge: 201

The minimum total cost of connec ons of all branches is: 0100

Prim's Algorithm
1. Input

2. Display

3. Minimum

4. Exit

Enter your choice:

*/

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal No: 8


Given sequence k = k1 <k2 < ... <kn of n sorted

keys, with a search probability pi for each key


ki . Build the Binary search tree that has the

least search cost given the access probability for

each key?

#include<iostream> using

namespace std;

void con_obst(void); void

print(int, int);

float a[20], b[20], wt[20][20], c[20][20];

int r[20][20], n;
int main()

{ int

i;

cout << "\n Program for Op mal Binary Search Tree (OBST)\n";

cout << "\nEnter the number of nodes: "; cin >> n;

cout << "\nEnter the probability for successful search:\n";

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

{ cout << "p[" << i <<

"]: "; cin >> a[i];

cout << "\nEnter the probability for unsuccessful search:\n";

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

{ cout << "q[" << i <<


"]: ";

cin >> b[i];

con_obst();

print(0, n); cout

<< endl; return

0;

void con_obst(void)
{ int i, j, k,

l;

// Ini aliza on for

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

{ c[i][i]
= 0.0;

r[i][i] = 0;

wt[i][i] = b[i];

wt[i][i + 1] = b[i] + b[i + 1] + a[i +


1]; c[i][i + 1] = b[i] + b[i + 1] + a[i +

1]; r[i][i + 1] = i + 1;

c[n][n] = 0.0;

r[n][n] = 0; wt[n][n]

= b[n];

// Fill c[][] and r[][] for j-i=2,3,4....,n for

(i = 2; i <= n; i++)

{ for (j = 0; j <= n - i;

j++)

{ wt[j][j + i] = b[j + i] + wt[j][j + i - 1]; c[j][j + i] =

9999; // Set to a large value to find the minimum cost

for (l = j + 1; l <= j + i; l++)


{ if (c[j][j + i] > (c[j][l - 1] +

c[l][j + i]))

c[j][j + i] = c[j][l - 1] + c[l][j +

i]; r[j][j + i] = l;

c[j][j + i] += wt[j][j + i];

cout << "\nOp mal BST is :\n"; cout <<

"w[0][" << n << "]:: " << wt[0][n] << endl; cout

<< "c[0][" << n << "]:: " << c[0][n] << endl;

cout << "r[0][" << n << "]:: " << r[0][n] << endl;

void print(int l1, int r1)

{ if (l1 >=
r1)

return;

int root = r[l1][r1]; // Get the root of the current subtree

if (root != 0)

{
// If the le child exists, print it if (r[l1][root - 1] != 0)

cout << "\nLe child of " << root << " is " << r[l1][root - 1];

// If the right child exists, print it if (r[root][r1] != 0)

cout << "\nRight child of " << root << " is " << r[root][r1];

// Recursively print le and right subtrees print(l1,

r[root][r1] - 1); // Le subtree print(r[root][r1], r1);

// Right subtree

Output:

/*Program for Op mal Binary Search Tree (OBST)

Enter the number of nodes: 2

Enter the probability for successful search: p[1]:


0.5

p[2]: 0.5

Enter the probability for unsuccessful

search: q[0]: 0.1 q[1]: 0.2 q[2]: 0.1


Op mal BST is :

w[0][2]:: 0.9

c[0][2]:: 1.7 r[0][2]::

Segmenta on fault (core dumped)

*/

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal No: 9


A Dic onary stores keywords & its meanings.
Provide facility for adding new keywords, dele ng
keywords, upda ng values of any entry. Provide
facility to display whole data sorted in ascending/
Descending order. Also find how many maximum
comparisons may require for finding any
keyword. Use Height balance tree and find the
complexity for finding a keyword

#include<iostream> using

namespace std;

struct HBTNode {
int Key;

char Mean[10];

HBTNode* le ;

HBTNode* right;

} *Root;

void create_HBT() {

int i; int nodes; int done; struct HBTNode*

Newnode, * current; cout << "\n\n Enter the number of

nodes to insert in HBT: "; cin >> nodes;

for(i = 0; i < nodes; i++) {

Newnode = new struct HBTNode;


cout << "\n\t Enter Keyword: ";
cin >> Newnode->Key; cout <<
"\n\t Enter the meaning: "; cin >>
Newnode->Mean; Newnode->le

= NULL;

Newnode->right = NULL;

if(Root == NULL) {

Root = Newnode;

} else { done = 0; current

= Root; while(!done)

{ if(Newnode>Key <

current->Key)
{ if(current->le == NULL)

{ current->le = Newnode;

done = 1; }

else { current =

current->le ;

} } else

{ if(current->right ==

NULL) {

current->right = Newnode;

done = 1; }

else { current =

current->right;

void display_HBT(struct HBTNode* root) {

if(root) {
cout << "\n\t" << root->Key << "_" << root>Mean;
display_HBT(root->le );

display_HBT(root->right);

}
void sorted_List(struct HBTNode* root) {

if(root) {

sorted_List(root->le ); cout << "\n\t" <<


root>Key << "_" << root->Mean; sorted_List(root-

>right);

void Find_Keyword(int Key)


{ int comp =
0; int level = 0;
int done; struct
HBTNode*

current;

done = 0; current = Root;

while(!done) { if(Key <

current->Key)

{ current =

current->le ;

level++; comp++;

} else if(Key > current->Key) { current

= current->right;

level++; comp++; } else


{ done = 1; comp++; cout

<< "\n\t Key: " << Key; cout << "\n\t Found
at Level: " << level; cout << "\n\t No. of

comparisons: " << comp;

int main() {
cout << "\n------***A C++ program to implement Dic onary using Height-Balanced
Tree.***-----\n";

cout << "\n 1. Store Keywords and Meanings in Height-Balanced

Tree."; Root = NULL; create_HBT();

cout << "\n2. Display Keywords and meanings in height balanced tree.";

cout << "\n keyword-meaning"; display_HBT(Root);

cout << "\n3. Display a sorted list of keywords and meanings.";

cout << "\n keyword-meaning"; sorted_List(Root);

cout << "\n4. Display Number of comparisons required to find a keyword.";

Find_Keyword(1);

return 0;

/*-----***A C++ program to implement Dic onary using Height-Balanced Tree.***-----

1. Store Keywords and Meanings in Height-Balanced Tree.


Enter the number of nodes to insert in HBT: 5

Enter Keyword: 3

Enter the meaning: Three

Enter Keyword: 2

Enter the meaning: Two

Enter Keyword: 4

Enter the meaning: FOur

Enter Keyword: 1

Enter the meaning: one

Enter Keyword: 5

Enter the meaning: Five

2. Display Keywords and meanings in height balanced tree. keyword-meaning

3_Three

2_Two
1_one

4_FOur

5_Five

3. Display a sorted list of keywords and meanings.

keyword-meaning

1_one

2_Two

3_Three

4_FOur

5_Five

4. Display Number of comparisons required to find a keyword.

Key: 1

Found at Level: 2

*/

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal 10:


Title: Read the marks obtained by students of second year in an online examina on of

par cular subject. Find out maximum and minimum marks obtained in that subject.

Use heap data structure. Analyze the algorithm.

Inputs: Marks of 07 Students. Output:

a) Create BST and display.

b) Convert BST into MAX Heap Tree and display.

c) Display Maximum Marks.


*/

#include<iostream> using

namespace std;

struct Node

int marks; struct

Node *le ; struct

Node *right;

}*root;

struct Node* createNode()

{
struct Node *tmp; tmp =
new struct Node;
cout<<"\n\t Enter Marks:
"; cin>>tmp->marks; tmp>le
= NULL; tmp->right =

NULL; return tmp;

void create_BST()

if(root == NULL)

{ root = createNode(); cout<<"\n\t ** Root


of

BST Tree is created ** ";


}

} void insert(struct Node *Root, struct Node

*newnode)

if(newnode->marks < Root->marks)

{
if(Root->le == NULL) Root-

>le = newnode;

else insert(Root->le ,

newnode);

} else

{
if(Root->right == NULL)

Root>right = newnode; else

insert(Root->right ,

newnode); }

} void preorder(struct Node

*Root)

if(Root != NULL)

cout<<" "<<Root-
>marks; preorder(Root-

>le ); preorder(Root-

>right);
}

}
//.....Func on to Convert BST into MAX Heap Tree void

MaxHeapify(struct Node *Parent)

{ int val; val =

Parent->right->marks;

Parent->right->marks = Parent->marks;

Parent->marks = val;

int main()

{ int cnt , i,

j;

struct Node *newnode;

cout<<"\n\n --------***Create and Display MAX Heap Tree***-------";

root = NULL; i = j = 0;

create_BST(); //.....Step 1: Create BST //.....Step 2:


Insert Nodes in BST
cout<<"\n\n How many nodes to insert? : "; cin>>cnt;

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

{ newnode = createNode();

insert(root , newnode);

}
//.....Step 3: Display BST cout<<"\n\n

Preorder Traversal: "; preorder(root);


//.....Step 4: Convert BST into MAX Heap Tree

MaxHeapify(root);

MaxHeapify(root->le );

MaxHeapify(root->right);
MaxHeapify(root); //.....Step 5: Display MAX
Heap Tree cout<<"\n\n A er Heapifying
BST........."; cout<<"\n\n Max Heap Tree
Preorder Traversal: "; preorder(root);

cout<<"\n\n\t Maximum Marks: "<<root-

>marks; cout<<"\n\n"; return 0;

Output:

--------***Create and Display MAX Heap Tree***-------

Enter Marks: 01

** Root of BST Tree is created **

How many nodes to insert? : 01

Enter Marks: 30
Enter Marks: 20

Enter Marks: 40

Enter Marks: 70

Enter Marks: 010

Enter Marks: 80

Preorder Traversal: 01 30 20 40 70 010 80

A er Heapifying BST.........

Max Heap Tree Preorder Traversal: 80 40 20 30 70 010 01

Maximum Marks: 80

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal No: 11


Department maintains a student informa on. The

file contains roll number, name, division and

address. Allow user to add, delete informa on of

student. Display informa on of par cular

employee. If record of student does not exist an

appropriate message is displayed. If it is, then the

system displays the student details. Use sequen al


file to main the data.

#include<iostream>
#include<fstream>

#include<cstring>

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,star
t4,n4;

char name[20],name2[20];

tel t1;

count=0; fstream

g,f; do

cout<<"\n>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<";

cout<<"\n1.Insert and overwrite\n2.Show\n3.Search & Edit(number)\n4.Search &


Edit(name)\n5.Search &

Edit(onlynumber)\n01.Search & edit(only name)\n 7.Delete a Student Record\n


8.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<<"\nDo you want

to enter more records?\n1.Yes\n2.No"; 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)));

//cout<<"\n\tRoll No.\t\tName \t\t Division \t\t Address"; while(f)

{ t1.show();

f.read((char*) &t1,(sizeof(t1)));

f.close(); break; case 3: cout<<"\nEnter the

roll number you want to find"; cin>>rec;

f.open("StuRecord.txt",ios::in|ios::out);
f.read((char*)&t1,(sizeof(t1)));

while(f) { if(rec==t1.rollNo)

cout<<"\nRecord found"; add=f.tellg();

f.seekg(0,ios::beg);

start=f.tellg(); n1=(add-start)/(sizeof(t1));

f.seekp((n1-1)*sizeof(t1),ios::beg); t1.accept();

f.write((char*) &t1,(sizeof(t1)));

f.close();

count++; break;
}

f.read((char*)&t1,(sizeof(t1)));

} if(count==0)

cout<<"\nRecord not found"; f.close(); break; case

4: cout<<"\nEnter the name you want to find and

edit"; cin>>name;

f.open("StuRecord.txt",ios::in|ios::out);
f.read((char*)&t1,(sizeof(t1))); while(f)

y=(strcmp(name,t1.name)); if(y==0)

cout<<"\nName found"; add2=f.tellg();

f.seekg(0,ios::beg); start2=f.tellg();

n2=(add2start2)/(sizeof(t1));

f.seekp((n2-1)*sizeof(t1),ios::beg); t1.accept();

f.write((char*) &t1,(sizeof(t1)));

f.close();

break; }

f.read((char*)&t1,(sizeof(t1))); }

break; case 5: cout<<"\n\tEnter the roll number you want to

modify"; cin>>on;

f.open("StuRecord.txt",ios::in|ios::out);
f.read((char*) &t1,(sizeof(t1)));

while(f) { if(on==t1.rollNo)

{
cout<<"\n\tNumber found"; add3=f.tellg();

f.seekg(0,ios::beg); start3=f.tellg();

n3=(add3start3)/(sizeof(t1));

f.seekp((n3-1)*(sizeof(t1)),ios::beg); t1.accept2();

f.write((char*)&t1,(sizeof(t1)));

f.close(); break;

f.read((char*)&t1,(sizeof(t1))); } break; case 01:

cout<<"\nEnter the name you want to find and

edit"; cin>>name2;

f.open("StuRecord.txt",ios::in|ios::out);

f.read((char*)&t1,(sizeof(t1)));

while(f)

y1=(strcmp(name2,t1.name)); if(y1==0)

cout<<"\nName found"; add4=f.tellg();

f.seekg(0,ios::beg); start4=f.tellg();

n4=(add4start4)/(sizeof(t1));

f.seekp((n4-1)*sizeof(t1),ios::beg); t1.accept3();

f.write((char*) &t1,(sizeof(t1)));

f.close(); break;

f.read((char*)&t1,(sizeof(t1)));

} break; case 7: 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);
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 8: cout<<"\n\tThank

you";

break;

}while(ch!=8);

}
Output :

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)


7.Delete a Student Record

8.Exit

Enter the Choice : 1

Enter Roll Number : 101

Enter the Name : Alice


Enter the Division: A Enter the

Address: Wonderland

Do you want to enter more records?

1.Yes

2.No: 1
Enter Roll Number : 102

Enter the Name : Bob

Enter the Division: B

Enter the Address: BuilderSt

Do you want to enter more records?

1.Yes

2.No: 1

Enter Roll Number : 103

Enter the Name : Carol


Enter the Division: C Enter

the Address: CandyLand

Do you want to enter more records?

1.Yes

2.No: 2

Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)

7.Delete a Student Record


8.Exit

Enter the Choice : 2

101 Alice A Wonderland

102 Bob B BuilderSt

103 Carol C CandyLand

Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)

7.Delete a Student Record

8.Exit

Enter the Choice : 3

Enter the roll number you want to find: 102

Record found

Enter Roll Number : 202

Enter the Name : Bobby

Enter the Division: D

Enter the Address: DreamTown


Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)


7.Delete a Student Record

8.Exit

Enter the Choice : 4

Enter the name you want to find and edit: Carol

Name found

Enter Roll Number : 303

Enter the Name : Caroline

Enter the Division: E

Enter the Address: EdenCity

Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show
3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)


7.Delete a Student Record

8.Exit

Enter the Choice : 5

Enter the roll number you want to modify: 101

Number found

Enter the Roll No. to modify : 111

Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)

7.Delete a Student Record

8.Exit

Enter the Choice : 01

Enter the name you want to find and edit: Bobby


Name found

Enter the name to modify : Robert

Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4.Search & Edit(name)

5.Search & Edit(onlynumber)

01.Search & edit(only name)

7.Delete a Student Record 8.Exit

Enter the Choice : 7

Please Enter the Roll No. of Student Whose Info You Want to Delete: 202

The record with the roll no. 202 has been deleted

Do you Want to Con nue in Main Menu....(y/n) : y

>>>>>>>>>>>>>>>>>>>>>>MENU<<<<<<<<<<<<<<<<<<<<<

1.Insert and overwrite

2.Show

3.Search & Edit(number)

4/Search & Edit(name)

5/Search & Edit(onlynumber)

01/Search & edit(only name)


7/Delete a Student Record

8.Exit

Enter the Choice : 2

111 Alice A Wonderland

303 Caroline E EdenCity

Do you Want to Con nue in Main Menu....(y/n) : n

Thank you

Name : Aher Ashish Vinod; Roll no: 01 ; Seat Number : S40001080101

Prac cal No:12

Title: A C++ Program to implement Random/Direct Access Files.

*/

#include<iostream>

#include<fstream> using

namespace std;

int main()
{

cout<<"\n\n ------*** Program to implement Random/Direct Access Files ***------\n\n";

ofstream fout;

fout.open("One.txt" , ios::out); cout<<"\n

Wri ng into the file.....\n";

cout<<"\n Loca on: "<<fout.tellp(); cout<<"

Line 01: Hello Dude, This is Sam...!!!";

fout<<"Hello Dude, This is Sam...!!!"<<endl;

cout<<"\n Loca on: "<<fout.tellp(); cout<<" Line 02:


Would you like to be my Friend..?";
fout<<"Would you like to be my Friend..?"<<endl; cout<<"\n
Loca on: "<<fout.tellp(); cout<<" Line

03: We will enjoy together...!!!";

fout<<"We will enjoy together...!!!"<<endl;

cout<<"\n Loca on: "<<fout.tellp()<<endl; fout.close();

ifstream fin;

fin.open("One.txt" , ios::in); cout<<"\n


Reading from the

file.....\n";
cout<<"\n Loca on: "<<fin.tellg();
cout<<"\n Shi control to...";
fin.seekg(014 , ios::beg);
cout<<"\n Loca on:
"<<fin.tellg(); cout<<" Reading....

"; char c; while(!fin.eof())

{ fin.get(c);

cout<<c;

} cout<<"\n Conclusion: We have Directly Accessed the line-03 of the

file."; fin.close();

return 0;

Output:

------*** Program to implement Random/Direct Access Files ***------

Wri ng into the file.....

Loca on: 0 Line 01: Hello Dude, This is Sam...!!!

Loca on: 30 Line 02: Would you like to be my Friend..?

Loca on: 014 Line 03: We will enjoy together...!!!


Loca on: 93

Reading from the file.....

Loca on: 0

Shi control to...

Loca on: 014 Reading.... We will enjoy together...!!!

Conclusion: We have Directly Accessed the line-03 of the file.

You might also like