Classes and Objects:
Q1: Create a class "Person" with attributes for name and age. Instantiate a few objects and print their details.
output.cpp
// C++ code
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person(string name, int age) : name(name), age(age) {}
void printDetails() {
cout << "Name: " << name << ", Age: " << age << endl;
}
private:
string name;
int age;
};
int main() {
// Instantiate objects of the "Person" class
Person person1("Alice", 30);
Person person2("Bob", 25);
Person person3("Charlie", 40);
// Print the details of each person
person1.printDetails();
person2.printDetails();
person3.printDetails();
return 0;
}
Q2: Implement a class "BankAccount" with methods for deposit and withdrawal. Enhance the "BankAccount" class with a method to check the account balance.
output.cpp
// C++ code
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
BankAccount(double initialBalance) {
balance = initialBalance;
}
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited $" << amount << endl;
} else {
cout << "Invalid deposit amount." << endl;
}
}
void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn $" << amount << endl;
} else {
cout << "Invalid withdrawal amount." << endl;
}
}
double checkBalance() {
return balance;
}
};
int main() {
BankAccount account(1000.0);
account.deposit(500.0);
account.withdraw(200.0);
double currentBalance = account.checkBalance();
cout << "Current Balance: $" << currentBalance << endl;
return 0;
}
Q3: Create a class "Student" with a constructor to initialize name and roll number.
output.cpp
// C++ code
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int rollNumber;
public:
// Constructor to initialize name and roll number
Student(string studentName, int studentRollNumber) : name(studentName), rollNumber(studentRollNumber) {
}
void displayInfo() {
cout << "Name: " << name << ", Roll Number: " << rollNumber << endl;
}
};
int main() {
// Instantiate a Student object with a constructor
Student student("Alice", 101);
// Display student information
student.displayInfo();
return 0;
}
Q4: Create a class "Book" with attributes title and author. Implement a method to display book information.
output.cpp
// C++ code
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
public:
Book(string bookTitle, string bookAuthor) : title(bookTitle), author(bookAuthor) {
}
void displayInfo() {
cout << "Title: " << title << ", Author: " << author << endl;
}
};
int main() {
Book book("The Catcher in the Rye", "J.D. Salinger");
book.displayInfo();
return 0;
}
Q5: Implement a class "Employee" with attributes like name, salary, and ID, and create objects for different employees.
output.cpp
// C++ code
#include <iostream>
#include <string>
using namespace std;
class Employee {
private:
string name;
double salary;
int id;
public:
Employee(string employeeName, double employeeSalary, int employeeID) : name(employeeName), salary(employeeSalary), id(employeeID) {
}
void displayInfo() {
cout << "Name: " << name << ", Salary: $" << salary << ", ID: " << id << endl;
}
};
int main() {
Employee employee1("Alice", 50000.0, 101);
Employee employee2("Bob", 60000.0, 102);
employee1.displayInfo();
employee2.displayInfo();
return 0;
}
Q6: Develop a class "Rectangle" with methods to calculate area and perimeter.
output.cpp
// C++ code
#include <iostream>
using namespace std;
class Rectangle {
private:
double length;
double width;
public:
Rectangle(double rectLength, double rectWidth) : length(rectLength), width(rectWidth) {
}
double calculateArea() {
return length * width;
}
double calculatePerimeter() {
return 2 * (length + width);
}
};
int main() {
Rectangle rect(5.0, 3.0);
double area = rect.calculateArea();
double perimeter = rect.calculatePerimeter();
cout << "Area: " << area << endl;
cout << "Perimeter: " << perimeter << endl;
return 0;
}
Q7: Design a class "Date" to represent dates and implement methods to compare dates and calculate the number of days between them.
output.cpp
// C++ code
#include <iostream>
using namespace std;
class Date {
private:
int day;
int month;
int year;
public:
Date(int d, int m, int y) : day(d), month(m), year(y) {
}
bool isLeapYear(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
int daysInMonth(int m, int y) {
int days[] = {0, 31, 28 + isLeapYear(y), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return days[m];
}
bool isValidDate() {
return (year >= 0 && month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(month, year));
}
int calculateDifference(const Date& otherDate) {
if (!isValidDate() || !otherDate.isValidDate()) {
return -1; // Invalid date(s)
}
int days1 = day;
for (int i = 0; i < month; i++) {
days1 += daysInMonth(i, year);
}
for (int i = 0; i < year; i++) {
days1 += (isLeapYear(i) ? 366 : 365);
}
int days2 = otherDate.day;
for (int i = 0; i < otherDate.month; i++) {
days2 += daysInMonth(i, otherDate.year);
}
for (int i = 0; i < otherDate.year; i++) {
days2 += (isLeapYear(i) ? 366 : 365);
}
return abs(days1 - days2);
}
};
int main() {
Date date1(2, 11, 2023);
Date date2(25, 12, 2023);
if (date1.isValidDate() && date2.isValidDate()) {
int difference = date1.calculateDifference(date2);
cout << "Number of days between the two dates: " << difference << endl;
} else {
cout << "Invalid date(s)." << endl;
}
return 0;
}
Q8: Create a class "ComplexNumber" for performing complex number arithmetic, including addition, subtraction, and multiplication.
output.cpp
// C++ code
#include <iostream>
using namespace std;
class ComplexNumber {
private:
double real;
double imaginary;
public:
ComplexNumber(double realPart, double imaginaryPart) : real(realPart), imaginary(imaginaryPart) {
}
ComplexNumber operator+(const ComplexNumber& other) {
return ComplexNumber(real + other.real, imaginary + other.imaginary);
}
ComplexNumber operator-(const ComplexNumber& other) {
return ComplexNumber(real - other.real, imaginary - other.imaginary);
}
ComplexNumber operator*(const ComplexNumber& other) {
return ComplexNumber(real * other.real - imaginary * other.imaginary, real * other.imaginary + imaginary * other.real);
}
void display() {
cout << real << " + " << imaginary << "i" << endl;
}
};
int main() {
ComplexNumber num1(3.0, 2.0);
ComplexNumber num2(1.5, 4.5);
ComplexNumber sum = num1 + num2;
ComplexNumber difference = num1 - num2;
ComplexNumber product = num1 * num2;
cout << "Sum: ";
sum.display();
cout << "Difference: ";
difference.display();
cout << "Product: ";
product.display();
return 0;
}
Q9: Develop a class "Library" to manage books, authors, and patrons, with methods for borrowing, returning, and searching books.
output.cpp
// C++ code
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Book {
public:
string title;
string author;
bool borrowed;
Book(const string& bookTitle, const string& bookAuthor)
: title(bookTitle), author(bookAuthor), borrowed(false) {
}
};
class Patron {
public:
string name;
Patron(const string& patronName) : name(patronName) {
}
};
class Library {
private:
vector<Book> books;
vector<Patron> patrons;
public:
void addBook(const string& title, const string& author) {
books.push_back(Book(title, author));
}
void addPatron(const string& name) {
patrons.push_back(Patron(name));
}
vector<Book> searchBooks(const string& query) {
vector<Book> results;
for (const Book& book : books) {
if (book.title.find(query) != string::npos || book.author.find(query) != string::npos) {
results.push_back(book);
}
}
return results;
}
bool borrowBook(Book& book, Patron& patron) {
if (book.borrowed) {
return false; // Book is already borrowed
}
book.borrowed = true;
return true;
}
bool returnBook(Book& book, Patron& patron) {
if (!book.borrowed) {
return false; // Book is not borrowed
}
book.borrowed = false;
return true;
}
};
int main() {
Library library;
library.addBook("Python Crash Course", "Eric Matthes");
library.addBook("The Great Gatsby", "F. Scott Fitzgerald");
library.addPatron("Alice");
library.addPatron("Bob");
vector<Book> searchResults = library.searchBooks("Python");
if (!searchResults.empty()) {
Book& bookToBorrow = searchResults[0];
Patron& patronBorrowing = library.patrons[0];
if (library.borrowBook(bookToBorrow, patronBorrowing)) {
cout << patronBorrowing.name << " borrowed " << bookToBorrow.title << "." << endl;
} else {
cout << bookToBorrow.title << " is not available for borrowing." << endl;
}
}
vector<Book> searchResults2 = library.searchBooks("Gatsby");
if (!searchResults2.empty()) {
Book& bookToReturn = searchResults2[0];
Patron& patronReturning = library.patrons[1];
if (library.returnBook(bookToReturn, patronReturning)) {
cout << patronReturning.name << " returned " << bookToReturn.title << "." << endl;
} else {
cout << bookToReturn.title << " was not borrowed by " << patronReturning.name << "." << endl;
}
}
// Display search results
cout << "Search results:" << endl;
for (const Book& book : searchResults) {
cout << book.title << " by " << book.author << endl;
}
return 0;
}