Practical No:1
Code:
#include <iostream>
#include <unordered_map>
using namespace std;
// Telephone Book Class using Hash Table
class TelephoneBook {
private:
unordered_map<string, string> phoneBook; // Hash table (key: name, value: phone number)
public:
// Insert a contact
void insertContact(string name, string number) {
phoneBook[name] = number;
cout << "Contact added: " << name << " -> " << number << endl;
// Search for a contact
void searchContact(string name) {
if (phoneBook.find(name) != phoneBook.end()) {
cout << "Phone Number of " << name << ": " << phoneBook[name] << endl;
} else {
cout << "Contact not found!" << endl;
// Delete a contact
void deleteContact(string name) {
if (phoneBook.erase(name)) {
cout << "Contact deleted: " << name << endl;
} else {
cout << "Contact not found!" << endl;
}
// Display all contacts
void displayContacts() {
if (phoneBook.empty()) {
cout << "Phone book is empty!" << endl;
return;
cout << "Telephone Book:" << endl;
for (auto &entry : phoneBook) {
cout << entry.first << " -> " << entry.second << endl;
};
// Driver Code
int main() {
TelephoneBook tb;
int choice;
string name, number;
do {
cout << "\n1. Insert Contact\n2. Search Contact\n3. Delete Contact\n4. Display Contacts\n5.
Exit\nEnter choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter Name: ";
cin >> name;
cout << "Enter Phone Number: ";
cin >> number;
tb.insertContact(name, number);
break;
case 2:
cout << "Enter Name to Search: ";
cin >> name;
tb.searchContact(name);
break;
case 3:
cout << "Enter Name to Delete: ";
cin >> name;
tb.deleteContact(name);
break;
case 4:
tb.displayContacts();
break;
case 5:
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid choice! Try again." << endl;
} while (choice != 5);
return 0;
}
Output:
1. Insert Contact
2. Search Contact
3. Delete Contact
4. Display Contacts
5. Exit
Enter choice: 1
Enter Name: Vaishnavi
Enter Phone Number: 7823822914
Contact added: Vaishnavi -> 7823822914
1. Insert Contact
2. Search Contact
3. Delete Contact
4. Display Contacts
5. Exit
Enter choice: 1
Enter Name: Pratiksha
Enter Phone Number: 9823720556
Contact added: Pratiksha -> 9823720556
1. Insert Contact
2. Search Contact
3. Delete Contact
4. Display Contacts
5. Exit
Enter choice: 2
Enter Name to Search: Vaishnavi
Phone Number of Vaishnavi: 7823822914
1. Insert Contact
2. Search Contact
3. Delete Contact
4. Display Contacts
5. Exit
Enter choice: 3
Enter Name to Delete: Vaishnavi
Contact deleted: Vaishnavi
1. Insert Contact
2. Search Contact
3. Delete Contact
4. Display Contacts
5. Exit
Enter choice: 4
Telephone Book:
Pratiksha -> 9823720556
1. Insert Contact
2. Search Contact
3. Delete Contact
4. Display Contacts
5. Exit
Enter choice: