Write a program to maintain a telephone directory. Use class and object with methods add() and show() to manage entries.

SOLUTION....


#include <iostream>
#include <string>
using namespace std;

class Directory {
private:
    string name[100];
    string phone[100];
    int count;

public:
    Directory() {
        count = 0;
    }

    // Method to add entry
    void add() {
        if (count < 100) {
            cout << "Enter name: ";
            cin >> name[count];
            cout << "Enter phone number: ";
            cin >> phone[count];
            count++;
            cout << "Entry added successfully!\n";
        } else {
            cout << "Directory is full!\n";
        }
    }

    // Method to show all entries
    void show() {
        if (count == 0) {
            cout << "No entries in the directory.\n";
        } else {
            cout << "\n--- Telephone Directory ---\n";
            for (int i = 0; i < count; i++) {
                cout << i + 1 << ". " << name[i] << " - " << phone[i] << endl;
            }
        }
    }
};

// Main function
int main() {
    Directory d;
    int choice;

    do {
        cout << "\n==== Telephone Directory Menu ====\n";
        cout << "1. Add Entry\n";
        cout << "2. Show Directory\n";
        cout << "3. Exit\n";
        cout << "Enter your choice: ";
        cin >> choice;

        switch (choice) {
            case 1: d.add(); break;
            case 2: d.show(); break;
            case 3: cout << "Exiting program...\n"; break;
            default: cout << "Invalid choice! Try again.\n";
        }
    } while (choice != 3);

    return 0;
}

OUTPUT

Leave a Reply

Your email address will not be published. Required fields are marked *