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 7 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 7 Design a class called cString to represent a string data type. Create a data member in the class to represent a string using an array of size 100. Write the following functionality as member functions: a. Copy Constructor b. Concatenate two strings c. Find the length of the string d. Reversing a string e. Comparing two strings

 


BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 7

Design a class called cString to represent a string data type. Create a data member in the class to represent a string using an array of size 100. 
Write the following functionality as member functions: 
a. Copy Constructor
 b. Concatenate two strings 
c. Find the length of the string 
d. Reversing a string
 e. Comparing two strings 

SOURCE CODE:
#include <iostream>
#include <cstring>
using namespace std;

class cString {
private:
    char str[100];  // Array to hold the string, fixed size of 100

public:
    // Default Constructor
    cString() {
        str[0] = '\0';  // Initialize with empty string
    }

    // Parameterized Constructor
    cString(const char* s) {
        strncpy(str, s, 99);
        str[99] = '\0';  // Ensure null termination
    }

    // Copy Constructor
    cString(const cString& other) {
        strncpy(str, other.str, 99);
        str[99] = '\0';  // Ensure null termination
    }

    // Function to concatenate two strings
    void concatenate(const cString& other) {
        strncat(str, other.str, 99 - strlen(str));  // Append with max size consideration
        str[99] = '\0';  // Ensure null termination
    }

    // Function to find the length of the string
    int length() const {
        return strlen(str);
    }

    // Function to reverse the string
    void reverse() {
        int len = strlen(str);
        for (int i = 0; i < len / 2; ++i) {
            swap(str[i], str[len - 1 - i]);
        }
    }

    // Function to compare two strings
    bool compare(const cString& other) const {
        return strcmp(str, other.str) == 0;
    }

    // Function to print the string
    void print() const {
        cout << str << std::endl;
    }
    // Function to read string from user
    void readFromUser() {
        cout << "Enter a string (max 99 characters): ";
        cin.getline(str, 100);
    }
};

int main() {
    cString s1,s2;
    
    // Read strings from user
    s1.readFromUser();
    s2.readFromUser();

    // Using Copy Constructor
    cString s3 = s1;

    // Concatenate strings
    s1.concatenate(s2);

    // Print strings
    cout << "s1: ";
    s1.print();
    cout << "s2: ";
    s2.print();
    cout << "s3: ";
    s3.print();

    // Find length of s1
    cout << "Length of s1: " << s1.length() << endl;
    // Find length of s2
    cout << "Length of s2: " << s2.length() << endl;

    // Reverse s1
    s1.reverse();
    cout << "Reversed s1: ";
    s1.print();
    // Reverse s2
    s2.reverse();
    cout << "Reversed s2: ";
    s2.print();

    // Compare s1 and s3
    cout << "s1 and s3 are " << (s1.compare(s3) ? "equal" : "not equal") << endl;

    return 0;
}

OUTPUT:
Enter a string (max 99 characters): hello
Enter a string (max 99 characters): world
s1: helloworld
s2: world
s3: hello
Length of s1: 10
Length of s2: 5
Reversed s1: dlrowolleh
Reversed s2: dlrow
s1 and s3 are not equal


Explanation:

  1. Data Member: The class cString has a private data member str which is a character array of size 100 to hold the string.

  2. Constructors:

    • Default Constructor initializes str with an empty string.
    • Parameterized Constructor initializes str with the given C-style string.
    • Copy Constructor copies the string from another cString object.
  3. Concatenate Function: The concatenate function appends the string from another cString object to the current string. It uses strncat to ensure that the array size limit is respected.

  4. Length Function: The length function returns the length of the string using strlen.

  5. Reverse Function: The reverse function reverses the string by swapping characters from the start and end moving towards the center.

  6. Compare Function: The compare function compares the string with another cString object using strcmp and returns true if they are equal.

  7. Print Function: The print function prints the string to the standard output.

Program 6 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 6 Design a 3x3 matrix class and demonstrate the following: a. Addition and multiplication of two matrices using operator overloading b. Maintaining a count of the number of matrix object created

 


BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 6

Design a 3x3 matrix class and demonstrate the following: 
a. Addition and multiplication of two matrices using operator overloading 
b. Maintaining a count of the number of matrix object created.


SOURCE CODE:

#include <iostream>
using namespace std;

class Matrix3x3 {
private:
    int data[3][3];
    static int objectCount; // Static variable to count the number of objects

public:
    // Constructor to initialize the matrix
    Matrix3x3(int init[3][3]) {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                data[i][j] = init[i][j];
            }
        }
        objectCount++;
    }

    // Default constructor
    Matrix3x3() {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                data[i][j] = 0;
            }
        }
        objectCount++;
    }

    // Destructor
    ~Matrix3x3() {
        objectCount--;
    }

    // Static function to get the number of objects
    static int getObjectCount() {
        return objectCount;
    }

    // Operator overloading for matrix addition
    Matrix3x3 operator+(const Matrix3x3& other) const {
        Matrix3x3 result;
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                result.data[i][j] = data[i][j] + other.data[i][j];
            }
        }
        return result;
    }

    // Operator overloading for matrix multiplication
    Matrix3x3 operator*(const Matrix3x3& other) const {
        Matrix3x3 result;
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                result.data[i][j] = 0;
                for (int k = 0; k < 3; ++k) {
                    result.data[i][j] += data[i][k] * other.data[k][j];
                }
            }
        }
        return result;
    }
// Function to read matrix from user input
    void readFromUser() {
        cout << "Enter the elements of the 3x3 matrix (row-wise):" << endl;
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                cin >> data[i][j];
            }
        }
    }

    // Function to print the matrix
    void print() const {
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                cout << data[i][j] << " ";
            }
            cout << endl;
        }
    }
};

// Initialize static member
int Matrix3x3::objectCount = 0;
int main() {
    Matrix3x3 matrix1, matrix2;
    
    cout << "Enter matrix 1:" << endl;
    matrix1.readFromUser();

    cout << "Enter matrix 2:" << endl;
    matrix2.readFromUser();

    cout << "Matrix 1:" << endl;
    matrix1.print();

    cout << "Matrix 2:" << endl;
    matrix2.print();

    Matrix3x3 matrixSum = matrix1 + matrix2;
    cout << "Sum of Matrix 1 and Matrix 2:" << endl;
    matrixSum.print();

    Matrix3x3 matrixProduct = matrix1 * matrix2;
    cout << "Product of Matrix 1 and Matrix 2:" << endl;
    matrixProduct.print();

    cout << "Number of Matrix3x3 objects created: " << Matrix3x3::getObjectCount() << endl;

    return 0;
}


OUTPUT:

Enter matrix 1:
Enter the elements of the 3x3 matrix (row-wise):
1 2  3
4 5 6
3 6 7
Enter matrix 2:
Enter the elements of the 3x3 matrix (row-wise):
3 3 3
2 2 2
1 1 1
Matrix 1:
1 2 3
4 5 6
3 6 7
Matrix 2:
3 3 3
2 2 2
1 1 1
Sum of Matrix 1 and Matrix 2:
4 5 6
6 7 8
4 7 8
Product of Matrix 1 and Matrix 2:
10 10 10
28 28 28
28 28 28
Number of Matrix3x3 objects created: 4


Explanation

  1. Matrix Class:

    • The readFromUser method is added to read matrix elements from the user.
    • The print method displays the matrix elements.
    • Other class members and methods remain unchanged.
  2. Main Function:

    • Two Matrix3x3 objects (matrix1 and matrix2) are created using the default constructor.
    • The readFromUser method is called to read the elements of each matrix from the user.
    • The matrices are displayed using the print method.
    • Addition and multiplication of the matrices are demonstrated using the overloaded operators.
    • The count of matrix objects is displayed using the static member function getObjectCount.

Program 5 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 5 Design a class representing time in hh:mm:ss. Write functions to a. Set and show the time b. Find the difference between two time objects c. Adding a given duration to a time d. Conversion of the time object to seconds

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 5

Design a class representing time in hh:mm:ss. Write functions to a. Set and show the time b. Find the difference between two time objects c. Adding a given duration to a time d. Conversion of the time object to seconds
 
SOURCE CODE:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

class Time {
private:
    int hours;
    int minutes;
    int seconds;

public:
    // Constructor to initialize time
    Time(int h = 0, int m = 0, int s = 0) : hours(h), minutes(m), seconds(s) {}

    // Function to set the time
    void setTime(int h, int m, int s) {
        hours = h;
        minutes = m;
        seconds = s;
    }

    // Function to show the time
    void showTime() const {
        cout << setw(2) << setfill('0') << hours << ":"
                  << setw(2) << setfill('0') << minutes << ":"
                  << setw(2) << setfill('0') << seconds << endl;
    }

    // Function to find the difference between two time objects
    Time difference(const Time &t) const {
        int totalSec1 = hours * 3600 + minutes * 60 + seconds;
        int totalSec2 = t.hours * 3600 + t.minutes * 60 + t.seconds;
        int diff = abs(totalSec1 - totalSec2);

        int h = diff / 3600;
        diff %= 3600;
        int m = diff / 60;
        int s = diff % 60;

        return Time(h, m, s);
    }

    // Function to add a given duration to a time
    void addDuration(int h, int m, int s) {
        int totalSec = hours * 3600 + minutes * 60 + seconds + h * 3600 + m * 60 + s;
        hours = (totalSec / 3600) % 24;
        totalSec %= 3600;
        minutes = (totalSec / 60) % 60;
        seconds = totalSec % 60;
    }

    // Function to convert the time object to seconds
    int toSeconds() const {
        return hours * 3600 + minutes * 60 + seconds;
    }
};

int main() {
    Time t1(2, 45, 30);
    Time t2(5, 50, 15);
    int h,m,s;

    cout << "Time 1: ";
    t1.showTime();

    cout << "Time 2: ";
    t2.showTime();

    Time diff = t1.difference(t2);
    cout << "Difference: ";
    diff.showTime();
    
    cout<<"Enter Hours, minutes and seconds to add to time 1:";
    cin>>h>>m>>s;
    t1.addDuration(h,m,s);
    cout << "Time 1 after adding given duration: ";
    t1.showTime();

    int seconds = t1.toSeconds();
    cout << "Time 1 in seconds: " << seconds << endl;

    return 0;
}


OUTPUT:

Time 1: 02:45:30
Time 2: 05:50:15
Difference: 03:04:45
Enter Hours, minutes and seconds to add to time 1:2 60 30
Time 1 after adding given duration: 05:46:00
Time 1 in seconds: 20760


Explanation:

  1. Constructor: Initializes the time with given hours, minutes, and seconds.
  2. setTime: Sets the time.
  3. showTime: Displays the time in hh:mm
    format.
  4. difference: Calculates the absolute difference between two time objects and returns the result as a new Time object.
  5. addDuration: Adds a given duration to the time object and adjusts for overflow in hours, minutes, and seconds.
  6. toSeconds: Converts the time to the total number of seconds since 00:00:00.


Program 4 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 4 Design and implement a class to represent a Solid object. a. Apart from data members to represent dimensions, use a data member to specify the type of solid. b. Use functions to calculate volume and surface area for different solids.

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 4

Design and implement a class to represent a Solid object. 

a. Apart from data members to represent dimensions, use a data member to specify the type of solid.
b. Use functions to calculate volume and surface area for different solids. 

SOURCE CODE:

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

class Solid {
protected:
    string type;

public:
    Solid(const string& type) : type(type) {}

    virtual ~Solid() {}

    string getType() const {
        return type;
    }

    virtual double volume() const = 0;
    virtual double surfaceArea() const = 0;
};
class Cube : public Solid {
private:
    double side;

public:
    Cube(double side) : Solid("Cube"), side(side) {}

    double volume() const override {
        return side * side * side;
    }

    double surfaceArea() const override {
        return 6 * side * side;
    }
};
class Sphere : public Solid {
private:
    double radius;

public:
    Sphere(double radius) : Solid("Sphere"), radius(radius) {}

    double volume() const override {
        return (4.0 / 3.0) * 3.14159265358979323846 * radius * radius * radius;
    }

    double surfaceArea() const override {
        return 4 * 3.14159265358979323846 * radius * radius;
    }
};
class Cylinder : public Solid {
private:
    double radius;
    double height;

public:
    Cylinder(double radius, double height) : Solid("Cylinder"), radius(radius), height(height) {}

    double volume() const override {
        return 3.14159265358979323846 * radius * radius * height;
    }

    double surfaceArea() const override {
        return 2 * 3.14159265358979323846 * radius * (radius + height);
    }
};
int main() {
    Cube cube(3);
    Sphere sphere(2);
    Cylinder cylinder(2, 5);

    Solid* solids[] = { &cube, &sphere, &cylinder };

    for (Solid* solid : solids) {
        cout << "Type: " << solid->getType() << endl;
        cout << "Volume: " << solid->volume() << endl;
        cout << "Surface Area: " << solid->surfaceArea() << endl;
        cout << std::endl;
    }

    return 0;
}

To design and implement a class to represent a Solid object in C++, we can use inheritance and polymorphism to handle different types of solids. Here, we'll create a base class Solid and derive specific classes for different types of solids, such as Cube, Sphere, and Cylinder. Each derived class will implement its own methods to calculate volume and surface area.

Here's an example of how this can be done:

Step-by-Step Implementation

  1. Base Class Solid:

    • Contains a data member to specify the type of solid.
    • Declares virtual functions to calculate volume and surface area.
  2. Derived Classes:

    • Implement specific solids like Cube, Sphere, and Cylinder.
    • Implement the methods to calculate volume and surface area.

Explanation

  1. Base Class Solid:

    • The Solid class has a protected data member type and a constructor to initialize it.
    • The class declares pure virtual functions volume() and surfaceArea(), making Solid an abstract class.
  2. Derived Classes (Cube, Sphere, Cylinder):

    • Each derived class initializes the base class with its type.
    • They override the volume() and surfaceArea() methods to provide specific implementations for each solid.
  3. Main Function:

    • Demonstrates how to create instances of different solids and call their methods to calculate volume and surface area.


OUTPUT:

Type: Cube

Volume: 27

Surface Area: 54


Type: Sphere

Volume: 33.5103

Surface Area: 50.2655


Type: Cylinder

Volume: 62.8319

Surface Area: 87.9646


Program 3 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 3Design and implement a class that represents a Harmonic Progression (HP). Implement functions to do the following: a. Generate the HP up to a specified number of terms b. Calculate the sum of the HP to n terms and to infinity c. Generate the nth term of the HP d. Generate the corresponding Arithmetic Progression. (Design and implement a class that encapsulates an AP, and allow the HP class to use its facilities by implementing friend functions.)

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 3

Design and implement a class that represents a Harmonic Progression (HP). Implement functions to do the following: a. Generate the HP up to a specified number of terms b. Calculate the sum of the HP to n terms and to infinity c. Generate the nth term of the HP d. Generate the corresponding Arithmetic Progression. (Design and implement a class that encapsulates an AP, and allow the HP class to use its facilities by implementing friend functions.)

SOURCE CODE:


#include <iostream>
#include <vector>
#include <limits>
#include <cmath> // For log and pow functions
using namespace std;

class ArithmeticProgression {
private:
    double a; // First term
    double d; // Common difference

public:
    ArithmeticProgression(double first_term, double common_difference)
        : a(first_term), d(common_difference) {}

    double nth_term(int n) const {
        return a + (n - 1) * d;
    }

    double sum_to_n_terms(int n) const {
        return n * (2 * a + (n - 1) * d) / 2;
    }

    vector<double> generate_terms(int n) const {
        vector<double> terms;
        for (int i = 1; i <= n; ++i) {
            terms.push_back(nth_term(i));
        }
        return terms;
    }

    friend class HarmonicProgression;
};



class HarmonicProgression {
private:
    ArithmeticProgression ap;

public:
    HarmonicProgression(double first_term, double common_difference)
        : ap(first_term, common_difference) {}

    double nth_term(int n) const {
        return 1.0 / ap.nth_term(n);
    }

    vector<double> generate_terms(int n) const {
        vector<double> terms;
        for (int i = 1; i <= n; ++i) {
            terms.push_back(nth_term(i));
        }
        return terms;
    }

    double sum_to_n_terms(int n) const {
        double sum = 0;
        for (int i = 1; i <= n; ++i) {
            sum += nth_term(i);
        }
        return sum;
    }

    double sum_to_infinity() const {
        if (ap.d == 0) {
            return numeric_limits<double>::infinity();
        }
        return numeric_limits<double>::infinity();
    }

    ArithmeticProgression corresponding_ap() const {
        return ap;
    }
};

int main() {
    HarmonicProgression hp(1, 1);
    int n;
    cout<<"Enter number of HP terms: ";
    cin>>n;
    cout << "First " << n << " terms of HP: ";
    vector<double> hp_terms = hp.generate_terms(n);
    for (double term : hp_terms) {
        cout << term << " ";
    }
    cout << std::endl;

    cout << "Sum of first " << n << " terms of HP: " << hp.sum_to_n_terms(n) << endl;
    cout << n << "th term of HP: " << hp.nth_term(n) << endl;
    cout << "Sum of HP to infinity: " << hp.sum_to_infinity() << endl;

    ArithmeticProgression ap = hp.corresponding_ap();
    cout << "First " << n << " terms of corresponding AP: ";
    vector<double> ap_terms = ap.generate_terms(n);
    for (double term : ap_terms) {
        cout << term << " ";
    }
    cout << endl;

    cout << "Sum of first " << n << " terms of AP: " << ap.sum_to_n_terms(n) << endl;
    cout << n << "th term of AP: " << ap.nth_term(n) << endl;

    return 0;
}

Explanation:

  1. ArithmeticProgression Class:

    • Represents an arithmetic progression with the first term aa and common difference dd.
    • Provides methods to calculate the nth term, sum of the first n terms, and generate the first n terms.
    • The HarmonicProgression class is declared as a friend to allow access to its private members.
  2. HarmonicProgression Class:

    • Contains an instance of the ArithmeticProgression class.
    • Provides methods to calculate the nth term of the HP, generate the first n terms of the HP, calculate the sum of the first n terms of the HP, and calculate the sum of the HP to infinity.
    • Returns the corresponding AP using the corresponding_ap method.
  3. Main Function:

    • Demonstrates the usage of the HarmonicProgression and ArithmeticProgression classes, including generating terms, calculating sums, and accessing corresponding AP terms.

OUTPUT:


Enter number of HP terms: 5
First 5 terms of HP: 1 0.5 0.333333 0.25 0.2 
Sum of first 5 terms of HP: 2.28333
5th term of HP: 0.2
Sum of HP to infinity: inf
First 5 terms of corresponding AP: 1 2 3 4 5
Sum of first 5 terms of AP: 15
5th term of AP: 5

Tuesday, July 2, 2024

Program 2 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 2 Write a Point class that represents a 2-d point in a plane. Write member functions to a. Set and show the value of a point b. Find the distance between two points c. Check whether two points are equal or not

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 2

Write a Point class that represents a 2-d point in a plane. Write member functions to a. Set and show the value of a point b. Find the distance between two points c. Check whether two points are equal or not

SOURCE CODE:
#include <iostream>
#include <cmath>
using namespace std;

class Point {
private:
    double x, y;

public:
    // Constructor
    Point(double x = 0, double y = 0) : x(x), y(y) {}

    // Set the value of the point
    void setPoint(double x, double y) {
        this->x = x;
        this->y = y;
    }

    // Show the value of the point
    void showPoint() const {
        cout << "Point(" << x << ", " << y << ")" << std::endl;
    }

    // Find the distance between two points
    double distanceTo(const Point &other) const {
        return sqrt(std::pow(x - other.x, 2) + std::pow(y - other.y, 2));
    }

    // Check whether two points are equal or not
    bool equals(const Point &other) const {
        return x == other.x && y == other.y;
    }
};

int main() {
    Point p1(1, 2);
    Point p2(4, 6);

    p1.showPoint();
    p2.showPoint();

    cout << "Distance between points: " << p1.distanceTo(p2) << std::endl;
    cout << "Points are equal: " << (p1.equals(p2) ? "Yes" : "No") << std::endl;

    return 0;
}


OUTPUT:

Point(1, 2)
Point(4, 6)
Distance between points: 5
Points are equal: No

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...