Monday, July 22, 2024

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 12

 Implement a telephone directory using files

SOURCE CODE:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

struct Contact {
    string name;
    string phoneNumber;
};
void addContact(const Contact& contact) {
    ofstream outFile("directory.txt", ios::app); // Open file in append mode
    if (outFile.is_open()) {
        outFile << contact.name << "," << contact.phoneNumber << endl;
        outFile.close();
    } else {
        cout << "Unable to open file." << endl;
    }
}
vector<Contact> loadContacts() {
    vector<Contact> contacts;
    ifstream inFile("directory.txt");
    if (inFile.is_open()) {
        string line;
        while (getline(inFile, line)) {
            size_t pos = line.find(',');
            if (pos != string::npos) {
                Contact contact;
                contact.name = line.substr(0, pos);
                contact.phoneNumber = line.substr(pos + 1);
                contacts.push_back(contact);
            }
        }
        inFile.close();
    } else {
        cout << "Unable to open file." << endl;
    }
    return contacts;
}
void searchContact(const string& name) {
    vector<Contact> contacts = loadContacts();
    bool found = false;
    for (const auto& contact : contacts) {
        if (contact.name == name) {
            cout << "Name: " << contact.name << ", Phone Number: " << contact.phoneNumber << endl;
            found = true;
            break;
        }
    }
    if (!found) {
        cout << "Contact not found." << endl;
    }
}
int main() {
    int choice;
    while (true) {
        cout << "1. Add Contact" << endl;
        cout << "2. Search Contact" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;
        cin.ignore(); // Ignore newline character left in the buffer

        if (choice == 1) {
            Contact contact;
            cout << "Enter name: ";
            getline(cin, contact.name);
            cout << "Enter phone number: ";
            getline(cin, contact.phoneNumber);
            addContact(contact);
        } else if (choice == 2) {
            string name;
            cout << "Enter name to search: ";
            getline(cin, name);
            searchContact(name);
        } else if (choice == 3) {
            break;
        } else {
            cout << "Invalid choice, please try again." << endl;
        }
    }
    return 0;
}

OUTPUT:
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 1
Enter name: ram
Enter phone number: 9488399999
1. Add Contact     
2. Search Contact  
3. Exit
Enter your choice: 1
Enter name: raj
Enter phone number: 9129320101
1. Add Contact     
2. Search Contact  
3. Exit
Enter your choice: 1
Enter name: gowri
Enter phone number: 9222122931
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 2
Enter name to search: ram
Name: ram, Phone Number: 9488399999
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 2
Enter name to search: ravi
Contact not found.
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 3


Explanation:

  1. Contact Structure: Holds the contact's name and phone number.
  2. File Operations:
    • addContact appends new contacts to the file.
    • loadContacts reads all contacts from the file into a vector.
    • searchContact searches for a contact by name and prints the result.
  3. Main Function: Provides a simple menu-driven interface for adding and searching contacts.

Program 11 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 11 Demonstrate the use of the vector STL container.

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 11

Demonstrate the use of the vector STL container.

SOURCE CODE:

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

int main() {
    // Create a vector of integers
    vector<int> numbers;

    // Add elements to the vector
    numbers.push_back(1);
    numbers.push_back(2);
    numbers.push_back(3);

    // Access elements using an index
    cout << "The first element is: " << numbers[0] << endl;

    // Iterate over the vector and print each element
    cout << "The elements in the vector are: ";
    for (const int& num : numbers) {
        cout << num << " ";
    }
    cout << endl;

    // Remove the last element
    numbers.pop_back();

    // Print the size of the vector
    cout << "The size of the vector after pop_back is: " << numbers.size() << endl;

    // Check if the vector is empty
    if (numbers.empty()) {
        cout << "The vector is empty." << endl;
    } else {
        cout << "The vector is not empty." << endl;
    }

    return 0;
}

OUTPUT:

The first element is: 1
The elements in the vector are: 1 2 3
The size of the vector after pop_back is: 2
The vector is not empty.

Explanation:

  1. Include the Header: #include <vector> is necessary to use the std::vector class.
  2. Create a Vector: std::vector<int> numbers; creates a vector of integers.
  3. Add Elements: push_back adds elements to the end of the vector.
  4. Access Elements: You can use the subscript operator [] to access elements.
  5. Iterate Over Elements: A range-based for loop is used to print all elements.
  6. Remove Elements: pop_back removes the last element.
  7. Check Size: size() returns the number of elements in the vector.
  8. Check if Empty: empty() returns true if the vector has no elements.

Program 10 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 10 Define a class template representing a single-dimensional array. Implement a function to sort the array elements. Include a mechanism to detect and throw an exception for array-bound violations.

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 10

Define a class template representing a single-dimensional array. Implement a function to sort the array elements. Include a mechanism to detect and throw an exception for array-bound violations.

SOURCE CODE:
#include <iostream>
#include <stdexcept> // For std::out_of_range
#include <algorithm> // For std::sort
using namespace std;

// Class template for a single-dimensional array
template <typename T>
class Array {
private:
    T* data;
    size_t size;

public:
    // Constructor
    Array(size_t size) : size(size) {
        data = new T[size];
    }

    // Destructor
    ~Array() {
        delete[] data;
    }

    // Copy constructor
    Array(const Array& other) : size(other.size) {
        data = new T[size];
        copy(other.data, other.data + size, data);
    }

    // Copy assignment operator
    Array& operator=(const Array& other) {
        if (this == &other) return *this; // Self-assignment check

        delete[] data; // Free the existing resource
        size = other.size;
        data = new T[size];
        copy(other.data, other.data + size, data);
        return *this;
    }

    // Move constructor
    Array(Array&& other) noexcept : data(other.data), size(other.size) {
        other.data = nullptr;
        other.size = 0;
    }

    // Move assignment operator
    Array& operator=(Array&& other) noexcept {
        if (this == &other) return *this; 

        delete[] data; // Free the existing resource
        data = other.data;
        size = other.size;
        other.data = nullptr;
        other.size = 0;
        return *this;
    }

    // Access element at index
    T& operator[](size_t index) {
        if (index >= size) {
            throw out_of_range("Index out of bounds");
        }
        return data[index];
    }

    const T& operator[](size_t index) const {
        if (index >= size) {
            throw out_of_range("Index out of bounds");
        }
        return data[index];
    }

    // Get the size of the array
    size_t getSize() const {
        return size;
    }

    // Sort the array using std::sort
    void sort() {
        std::sort(data, data + size);
    }

    // Print array elements
    void print() const {
        for (size_t i = 0; i < size; ++i) {
            cout << data[i] << ' ';
        }
        cout << endl;
    }
};


int main() {
    try {
        Array<int> arr(5);

        for (size_t i = 0; i < arr.getSize(); ++i) {
            arr[i] = 5 - i; // Fill array with values
        }

        cout << "Original array: ";
        arr.print();

        arr.sort();

        cout << "Sorted array: ";
        arr.print();

        // exception handling
        cout << "Trying to access out-of-bounds index: ";
        cout << "Trying to print 10 th index element: "<<endl;
        cout << arr[10] << endl; // This will throw an exception
    }
    catch (const out_of_range& e) {
        cerr << "Exception: " << e.what() << endl;
    }

    return 0;
}

OUTPUT:
Original array: 5 4 3 2 1 
Sorted array: 1 2 3 4 5
Trying to access out-of-bounds index: Trying to print 10 th index element:
Exception: Index out of bounds

Explanation:

  1. Class Template Definition:

    • Array(size_t size): Constructor that initializes the array with the given size.
    • ~Array(): Destructor that frees allocated memory.
    • Copy and move constructors/operators are provided to handle deep copying and move semantics.
    • operator[]: Provides access to array elements and throws an std::out_of_range exception if an invalid index is accessed.
  2. Sorting:

    • sort(): Uses std::sort from the <algorithm> header to sort the array elements.
  3. Exception Handling:

    • Out-of-bounds access is handled by throwing std::out_of_range if an invalid index is used.

Program 9 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 9 Create a class to represent a 2-d shape and derive classes to represent a triangle, rectangle and circle. Write a program using run-time polymorphism to compute the area of the figures.

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 9

Create a class to represent a 2-d shape and derive classes to represent a triangle, rectangle and circle. Write a program using run-time polymorphism to compute the area of the figures.

SOURCE CODE:

#include <iostream>
#include <cmath> // for M_PI
using namespace std;

// Base class for 2D shapes
class Shape {
public:
    virtual double area() const = 0; // Pure virtual function to compute area
    virtual ~Shape() = default;      // Virtual destructor
};

// Derived class for Triangle
class Triangle : public Shape {
private:
    double base;
    double height;

public:
    Triangle(double b, double h) : base(b), height(h) {}

    double area() const override {
        cout<<"Triangle Shape"<<endl;
        return 0.5 * base * height;
    }
};

// Derived class for Rectangle
class Rectangle : public Shape {
private:
    double width;
    double height;

public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override {
                cout<<"Rectangle Shape"<<endl;
        return width * height;
    }
};

// Derived class for Circle
class Circle : public Shape {
private:
    double radius;

public:
    Circle(double r) : radius(r) {}

    double area() const override {
        cout<<"Circle Shape"<<endl;

        return M_PI * radius * radius;
    }
};

int main() {
    // Creating objects for each shape
    Shape* shapes[] = {
        new Triangle(3.0, 4.0),
        new Rectangle(5.0, 6.0),
        new Circle(7.0)
    };

    // Computing and displaying the area of each shape
    for (Shape* shape : shapes) {
        cout << "Area: " << shape->area() << endl;
    }

    // Cleaning up dynamically allocated memory
    for (Shape* shape : shapes) {
        delete shape;
    }

    return 0;
}

OUTPUT:

Triangle Shape
Area: 6
Rectangle Shape
Area: 30
Circle Shape
Area: 153.938


Explanation:

  1. Base Class Shape:

    • Shape is an abstract base class with a pure virtual function area().
    • The destructor is virtual to ensure proper cleanup of derived class objects.
  2. Derived Classes:

    • Triangle, Rectangle, and Circle classes inherit from Shape.
    • Each class implements the area() function to calculate the area specific to the shape.
  3. Main Function:

    • An array of pointers to Shape objects is created, each pointing to a different shape.
    • The area() function is called on each shape object, demonstrating runtime polymorphism.
    • Memory allocated with new is released with delete.

Program 8 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 8 Design a class called cString to represent a string data type. Create a data member in the class to represent a string whose size is dynamically allocated. Write the following as member functions: a. Copy Constructor b. Destructor c. Concatenate two strings d. Find the length of the string e. Reversing a string f. Comparing two strings

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 8

Design a class called cString to represent a string data type. Create a data member in the class to represent a string whose size is dynamically allocated. Write the following as member functions: a. Copy Constructor b. Destructor c. Concatenate two strings d. Find the length of the string e. Reversing a string f. Comparing two strings
 
SOURCE CODE:

#include <iostream>
#include <cstring> // for strlen, strcpy, strcmp
using namespace std;

class cString {
private:
    char* str;

public:
    // Default constructor
    cString() : str(nullptr) {}

    // Parameterized constructor
    cString(const char* s) {
        str = new char[strlen(s) + 1];
        strcpy(str, s);
    }

    // Copy constructor
    cString(const cString& other) {
        str = new char[strlen(other.str) + 1];
        strcpy(str, other.str);
    }

    // Destructor
    ~cString() {
        delete[] str;
    }

    // Concatenate two strings
    void concatenate(const cString& other) {
        char* temp = new char[strlen(str) + strlen(other.str) + 1];
        strcpy(temp, str);
        strcat(temp, other.str);
        delete[] str;
        str = temp;
    }

    // Find the length of the string
    size_t length() const {
        return strlen(str);
    }

    // Reverse the string
    void reverse() {
        size_t len = strlen(str);
        for (size_t i = 0; i < len / 2; ++i) {
            std::swap(str[i], str[len - i - 1]);
        }
    }

    // Compare two strings
    int compare(const cString& other) const {
        return strcmp(str, other.str);
    }

    // Overload the assignment operator
    cString& operator=(const cString& other) {
        if (this == &other) {
            return *this;
        }

        delete[] str;
        str = new char[strlen(other.str) + 1];
        strcpy(str, other.str);
        return *this;
    }

    // Overload the stream insertion operator for easy printing
    friend std::ostream& operator<<(std::ostream& os, const cString& s) {
        os << s.str;
        return os;
    }
};

int main() {
    cString s1("Hello");
    cString s2("World");
    cString s3(s1);

    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
     cout<< "s3: " << s3 << endl;

    s3.concatenate(s2);
    cout << "Concatenated s3: " << s3 << endl;

    cout << "Length of s3: " << s3.length() << endl;

    s3.reverse();
    cout << "Reversed s3: " << s3 << endl;

    int cmp = s1.compare(s2);
    cout << "Comparison of s1 and s2: " << cmp << endl;

    return 0;
}


OUTPUT:

s1: Hello
s2: World
s3: Hello
Concatenated s3: HelloWorld
Length of s3: 10
Reversed s3: dlroWolleH
Comparison of s1 and s2: -1

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...