Assignment 1
Assignment 1
Assignment 1
Here are some exercises that you can use to practice working with classes and objects in C++:
Create a Book class with attributes such as title, author, and ISBN. Include methods to display
book details and set book details.
Design a BankAccount class with methods like deposit, withdraw, and getBalance. Ensure you
have a constructor to set an initial balance.
Create a Student class with attributes like name, rollNumber, and marks. Implement methods to
calculate the grade based on the marks.
Develop a Car class that contains attributes like make, model, year, and speed. Include methods
like accelerate and brake.
Develop a Library class that contains a collection of books (Book objects). Implement methods
to add a book, remove a book, and display all books.
1. Question: Create a Car class with attributes brand, model, and year. Provide methods to
set and display these attributes.
Answer:
#include <iostream>
#include <string>
class Car {
private:
string brand;
string model;
int year;
public:
// Constructor
// Setter method
brand = b;
model = m;
year = y;
// Display method
void displayDetails() {
cout << “Brand: ” << brand << “, Model: ” << model << “, Year: ” << year << endl;
};
int main() {
Car myCar(“Toyota”, “Camry”, 2020);
myCar.displayDetails();
// Update details
myCar.displayDetails();
return 0;
2. Question: Create a Rectangle class with attributes length and width. Include methods to
calculate the area and perimeter of the rectangle.
Answer:
#include <iostream>
class Rectangle {
private:
double length;
double width;
public:
// Constructor
double calculateArea() {
double calculatePerimeter() {
};
int main() {
Rectangle rect(5.0, 3.0);
return 0;
3. Question: Define a Book class with attributes title, author, and isbn. Provide methods to
set and display these attributes.
Answer:
#include <iostream>
#include <string>
class Book {
private:
string title;
string author;
string isbn;
public:
// Constructor
// Setter method
title = t;
author = a;
isbn = i;
// Display method
void displayDetails() {
cout << “Title: ” << title << “, Author: ” << author << “, ISBN: ” << isbn << endl;
}
};
int main() {
myBook.displayDetails();
// Update details
myBook.displayDetails();
return 0;