0% found this document useful (0 votes)
32 views22 pages

OOPC Programming Exercises Overview

The document contains multiple programming exercises focused on object-oriented programming concepts in C++. It includes tasks such as creating classes for Student and Teacher to evaluate grades, simulating an ATM system for customer transactions, and managing book records in a library. Each exercise is accompanied by code examples and expected outputs, demonstrating the implementation of various programming principles including constructors, operator overloading, and default arguments.

Uploaded by

souravm.it.23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views22 pages

OOPC Programming Exercises Overview

The document contains multiple programming exercises focused on object-oriented programming concepts in C++. It includes tasks such as creating classes for Student and Teacher to evaluate grades, simulating an ATM system for customer transactions, and managing book records in a library. Each exercise is accompanied by code examples and expected outputs, demonstrating the implementation of various programming principles including constructors, operator overloading, and default arguments.

Uploaded by

souravm.it.23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ASSIGNMENT 2

OOPC Programming Exercise


QUESTION 1
Create a system where the class Student holds private data about a student’s name and grades, and
the class Teacher evaluates the student. The Teacher class has a function that accepts a Student
object as an argument and calculates the grade point average (GPA) based on the grades. The
function should print a message based on the GPA (e.g., " Excellent" if GPA>9, "
Good & quot; if GPA & gt; 7,etc.). Make sure to handle a situation where a student has no grades
entered.
CODE:-
#include <iostream>
using namespace std;
class Student {
private:
string name;
double grades[10];
int gradeCount;
public:
Student(string studentName) : name(studentName), gradeCount(0) {}
void addGrade(double grade) {
if (gradeCount < 10) {
if (grade >= 0 && grade <= 10) {
grades[gradeCount++] = grade;
} else {
cout << "Grade must be between 0 and 10." << endl;
}
} else {
cout << "Cannot add more than 10 grades." << endl;
}
}
string getName() const {
return name;
}

1
VANSHAM MAHAJAN 23124117
int getGradeCount() const {
return gradeCount;
}
const double* getGrades() const {
return grades;
}
};
class Teacher {
public:
void evaluateStudent(const Student& student) const {
int gradeCount = [Link]();
if (gradeCount == 0) {
cout << [Link]() << " has no grades entered." << endl;
return;
}
const double* grades = [Link]();
double sum = 0.0;
for (int i = 0; i < gradeCount; ++i) {
sum += grades[i];
}
double gpa = sum / gradeCount;
cout << "GPA: " << gpa << " - ";
if (gpa > 9) {
cout << "Excellent" << endl;
} else if (gpa > 7) {
cout << "Good" << endl;
} else if (gpa > 5) {
cout << "Average" << endl;
} else {
cout << "Needs Improvement" << endl;
}
}

2
VANSHAM MAHAJAN 23124117
};
int main() {
Student student1("John Doe");
[Link](8.5);
[Link](9.0);
[Link](7.5);
Student student2("Jane Smith");
Teacher teacher;
[Link](student1);
[Link](student2);
return 0;
}
OUTPUT:-

3
VANSHAM MAHAJAN 23124117
QUESTION 2
Write a program simulating an ATM where the Customer class contains information about the
customer’s account balance. Another class ATM has a function that accepts a Customer object and
performs operations like withdrawal and balance checking. The ATM class should not allow a
withdrawal if the customer has insufficient funds. Handle the case where the customer tries to
withdraw more than available balance and ensure that the withdrawal process updates the balance
correctly.

CODE:-
#include <iostream>
using namespace std;
class Customer {
private:
string name;
double balance;
public:
Customer(string customerName, double initialBalance) : name(customerName),
balance(initialBalance) {}
string getName() const {
return name;
}
double getBalance() const {
return balance;
}
void updateBalance(double amount) {
balance += amount;
}
};
class ATM {
public:
void checkBalance(const Customer& customer) const {
cout << [Link]() << ", your current balance is: $" << [Link]() << endl;
}
void withdraw(Customer& customer, double amount) {
if (amount <= 0) {

4
VANSHAM MAHAJAN 23124117
cout << "Withdrawal amount must be greater than 0." << endl;
return;
}
if (amount > [Link]()) {
cout << "Insufficient funds. Unable to withdraw $" << amount << "." << endl;
} else {
[Link](-amount);
cout << "Withdrawal successful. $" << amount << " has been withdrawn." << endl;
checkBalance(customer);
}
}
};
int main() {
Customer customer1("John Doe", 1000.0);
ATM atm;
[Link](customer1);
[Link](customer1, 300.0);
[Link](customer1, 800.0);
[Link](customer1, -50.0);
return 0;
}
OUTPUT:-

5
VANSHAM MAHAJAN 23124117
QUESTION 3
You are building a system for an online bookstore where each Book object is initialized
dynamically with data like title , author , price , and availableCopies . Overload the constructor of
the Book class such that it allows creating a Book object with partial data (e.g., without
availableCopies ) and full data. Additionally, write a program that dynamically initializes an array of
Book objects and adjusts the availableCopies based on the stock received from the publisher. Ensure
that the stock adjustment happens only when new copies are delivered.

CODE:-
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
string author;
double price;
int availableCopies;
public:
Book() : title(""), author(""), price(0.0), availableCopies(0) {}
Book(string t, string a, double p) : title(t), author(a), price(p), availableCopies(0) {}
Book(string t, string a, double p, int copies) : title(t), author(a), price(p), availableCopies(copies) {}
string getTitle() const {
return title;
}
string getAuthor() const {
return author;
}
double getPrice() const {
return price;
}
int getAvailableCopies() const {
return availableCopies;
}
void adjustStock(int newCopies) {

6
VANSHAM MAHAJAN 23124117
if (newCopies > 0) {
availableCopies += newCopies;
cout << "Stock updated. New available copies of \"" << title << "\": " << availableCopies <<
endl;
} else {
cout << "Invalid stock adjustment. Copies must be greater than 0." << endl;
}
}
};
int main() {
int numBooks = 3;
Book* bookArray = new Book[numBooks];
bookArray[0] = Book("The Great Gatsby", "F. Scott Fitzgerald", 10.99);
bookArray[1] = Book("To Kill a Mockingbird", "Harper Lee", 12.99, 5);
bookArray[2] = Book("1984", "George Orwell", 15.99, 8);
bookArray[0].adjustStock(10);
bookArray[1].adjustStock(5);
bookArray[2].adjustStock(7);
delete[] bookArray;
return 0;
}
OUTPUT:-

7
VANSHAM MAHAJAN 23124117
QUESTION 4
You are building a ticket booking system for a bus company. The company allows users to book
tickets either with or without specifying additional options like food service and extra luggage
allowance. Write a function `bookTicket()` that allows a passenger to book a ticket with a default
argument for food service and luggage. Use both call by value and call by reference to show how the
ticket booking information is modified.

CODE:-
#include <iostream>
#include <string>
using namespace std;
class Passenger {
private:
string name;
int ticketNumber;
bool foodService;
int luggageAllowance;
public:
Passenger(string passengerName, int ticketNum)
: name(passengerName), ticketNumber(ticketNum), foodService(false), luggageAllowance(0) {}
void displayInfo() const {
cout << "Passenger Name: " << name << endl;
cout << "Ticket Number: " << ticketNumber << endl;
cout << "Food Service: " << (foodService ? "Yes" : "No") << endl;
cout << "Luggage Allowance: " << luggageAllowance << " kg" << endl;
}
void bookTicket(bool food = false, int luggage = 0) {
foodService = food;
luggageAllowance = luggage;
cout << "Ticket booked successfully!" << endl;
}
};
void bookTicketByValue(Passenger passenger) {
[Link](true, 20);
cout << "After booking by value:" << endl;

8
VANSHAM MAHAJAN 23124117
[Link]();
}
void bookTicketByReference(Passenger& passenger) {
[Link](false, 10);
cout << "After booking by reference:" << endl;
[Link]();
}
int main() {
Passenger passenger1("John Doe", 101);
cout << "Initial passenger info:" << endl;
[Link]();
bookTicketByValue(passenger1);
cout << "Passenger info after booking by value:" << endl;
[Link]();
bookTicketByReference(passenger1);
cout << "Passenger info after booking by reference:" << endl;
[Link]();
return 0;
}
OUTPUT:-

9
VANSHAM MAHAJAN 23124117
QUESTION 5
Write a program to demonstrate the use of default arguments. Create a function `calculatePrice()`
that calculates the total price of an item, including tax and shipping. Tax should default to 5% and
shipping to $10 if no values are passed. Create multiple function calls to demonstrate how default
arguments work.

CODE:-
#include <iostream>
#include <iomanip>
using namespace std;
double calculatePrice(double itemPrice, double tax = 0.05, double shipping = 10.0) {
double totalPrice = itemPrice + (itemPrice * tax) + shipping;
return totalPrice;
}
int main() {
double itemPrice;
cout << "Enter the item price: $";
cin >> itemPrice;
double price1 = calculatePrice(itemPrice);
cout << fixed << setprecision(2);
cout << "Total price (default tax and shipping): $" << price1 << endl;
double customTax = 0.08;
double price2 = calculatePrice(itemPrice, customTax);
cout << "Total price (custom tax, default shipping): $" << price2 << endl;
double customShipping = 15.0;
double price3 = calculatePrice(itemPrice, customTax, customShipping);
cout << "Total price (custom tax and shipping): $" << price3 << endl;
double price4 = calculatePrice(itemPrice, 0.05, customShipping);
cout << "Total price (default tax, custom shipping): $" << price4 << endl;
return 0;
}
OUTPUT:-

10
VANSHAM MAHAJAN 23124117
QUESTION 6
Imagine you are developing a library management system. Create a `Book` class that includes a title
and the number of available copies. Write a function `borrowBook` that takes a reference to the
number of copies and a string title as parameters. If the number of available copies is greater than
zero, decrease the count by one and confirm the borrowing process. Otherwise, indicate that the
book is not available.

CODE:-
#include <iostream>
#include <string>
using namespace std;
class Book {
private:
string title;
int availableCopies;
public:
Book(string bookTitle, int copies) : title(bookTitle), availableCopies(copies) {}
void displayInfo() const {
cout << "Title: " << title << ", Available Copies: " << availableCopies << endl;
}
void borrowBook() {
if (availableCopies > 0) {
availableCopies--;
cout << "You have successfully borrowed \"" << title << "\"." << endl;
} else {
cout << "Sorry, \"" << title << "\" is not available." << endl;
}
}
};
int main() {
Book book1("The Catcher in the Rye", 3);
[Link]();
[Link]();
[Link]();
[Link]();

11
VANSHAM MAHAJAN 23124117
[Link]();
[Link]();
[Link]();
[Link]();
return 0;
}
OUTPUT:-

12
VANSHAM MAHAJAN 23124117
QUESTION 7
You are tasked with building a system to manage academic records. Each Record object stores
information about the student’s name, ID, and an array of 5 exam scores. The system needs to
duplicate records when a student transfers departments, and it should be done in a way that each
transferred record is an exact copy, but changes to one record should not affect the other.

CODE:-
#include <iostream>
#include <string>
using namespace std;
class Record {
private:
string studentName;
int studentID;
double examScores[5];
public:
Record(string name, int id, double scores[5]) {
studentName = name;
studentID = id;
for (int i = 0; i < 5; i++) {
examScores[i] = scores[i];
}
}
Record(const Record& other) {
studentName = [Link];
studentID = [Link];
for (int i = 0; i < 5; i++) {
examScores[i] = [Link][i];
}
}
void displayRecord() const {
cout << "Student Name: " << studentName << endl;
cout << "Student ID: " << studentID << endl;
cout << "Exam Scores: ";

13
VANSHAM MAHAJAN 23124117
for (int i = 0; i < 5; i++) {
cout << examScores[i] << " ";
}
cout << endl;
}
void modifyScore(int index, double newScore) {
if (index >= 0 && index < 5) {
examScores[index] = newScore;
} else {
cout << "Invalid score index." << endl;
}
}
};
int main() {
double scores[5] = {85.5, 90.0, 78.0, 88.5, 92.0};
Record originalRecord("Alice Smith", 12345, scores);
cout << "Original Record:" << endl;
[Link]();
Record transferredRecord = originalRecord;
cout << "\nTransferred Record:" << endl;
[Link]();
[Link](0, 95.0);
cout << "\nAfter modifying the transferred record's score:" << endl;
cout << "Original Record:" << endl;
[Link]();
cout << "\nTransferred Record:" << endl;
[Link]();
return 0;
}
OUTPUT:-

14
VANSHAM MAHAJAN 23124117
15
VANSHAM MAHAJAN 23124117
QUESTION 8
Write a C++program to create a class `Student` that stores marks of a student in 3 subjects. Define a
parameterized constructor to initialize the marks. Overload the `+` operator to add the marks of two
students and find out which student has scored higher.

CODE:-
#include <iostream>
using namespace std;
class Student {
private:
int marks[3];
public:
Student(int m1, int m2, int m3) {
marks[0] = m1;
marks[1] = m2;
marks[2] = m3;
}
Student operator+(const Student& other) {
return Student(marks[0] + [Link][0],
marks[1] + [Link][1],
marks[2] + [Link][2]);
}
int totalMarks() const {
return marks[0] + marks[1] + marks[2];
}
void displayMarks() const {
cout << "Marks: " << marks[0] << ", " << marks[1] << ", " << marks[2] << endl;
}
};
int main() {
Student student1(85, 90, 80);
Student student2(75, 88, 92);
cout << "Student 1: ";
[Link]();

16
VANSHAM MAHAJAN 23124117
cout << "Student 2: ";
[Link]();
Student totalMarks = student1 + student2;
cout << "Total Marks (Student 1 + Student 2): ";
[Link]();
if ([Link]() > [Link]()) {
cout << "Student 1 scored higher." << endl;
} else if ([Link]() < [Link]()) {
cout << "Student 2 scored higher." << endl;
} else {
cout << "Both students scored the same." << endl;
}
return 0;
}
OUTPUT:-

17
VANSHAM MAHAJAN 23124117
QUESTION 9
Design a`Matrix`class to represent a 2D matrix. Overload the constructor to initialize matrices of
different sizes dynamically. One constructor should take the number of rows and columns, another
should take only one size for square matrices, and a default constructor should initialize a 2x2
matrix. Also, implement a function that displays the matrix and initialize several matrices
dynamically.

CODE:-
#include <iostream>
using namespace std;
class Matrix {
private:
int rows;
int cols;
int** data;
public:
Matrix() {
rows = 2;
cols = 2;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols]{0};
}
}
Matrix(int size) {
rows = size;
cols = size;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols]{0};
}
}
Matrix(int r, int c) {
rows = r;
cols = c;

18
VANSHAM MAHAJAN 23124117
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols]{0};
}
}
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}
void setValue(int r, int c, int value) {
if (r >= 0 && r < rows && c >= 0 && c < cols) {
data[r][c] = value;
} else {
cout << "Index out of bounds!" << endl;
}
}
void display() const {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << data[i][j] << " ";
}
cout << endl;
}
}
};
int main() {
Matrix matrix1;
cout << "Default 2x2 Matrix:" << endl;
[Link]();
Matrix matrix2(3);

19
VANSHAM MAHAJAN 23124117
[Link](0, 0, 1);
[Link](1, 1, 2);
[Link](2, 2, 3);
cout << "\n3x3 Square Matrix:" << endl;
[Link]();
Matrix matrix3(2, 3);
[Link](0, 0, 4);
[Link](0, 1, 5);
[Link](0, 2, 6);
[Link](1, 0, 7);
[Link](1, 1, 8);
[Link](1, 2, 9);
cout << "\n2x3 Rectangular Matrix:" << endl;
[Link]();
return 0;
}
OUTPUT:-

20
VANSHAM MAHAJAN 23124117
QUESTION 10
In a weather monitoring application, you have a `WeatherData` class that keeps track of temperature
and humidity. Write a function `updateWeatherData` that accepts the temperature and humidity
values by reference and updates the class attributes accordingly. Show the effects of using call by
reference versus call by value by attempting to update the data from the main function.

CODE:-
#include <iostream>
using namespace std;
class WeatherData {
private:
double temperature;
double humidity;
public:
WeatherData(double temp, double hum) : temperature(temp), humidity(hum) {}
void updateWeatherData(double& tempRef, double& humRef) {
temperature = tempRef;
humidity = humRef;
}
void display() const {
cout << "Temperature: " << temperature << " °C" << endl;
cout << "Humidity: " << humidity << " %" << endl;
}
void updateWeatherDataByValue(double tempVal, double humVal) {
temperature = tempVal;
humidity = humVal;
}
};
int main() {
WeatherData weather(25.0, 60.0);
cout << "Initial Weather Data:" << endl;
[Link]();
double newTempRef = 30.0;
double newHumRef = 55.0;

21
VANSHAM MAHAJAN 23124117
[Link](newTempRef, newHumRef);
cout << "\nWeather Data after call by reference update:" << endl;
[Link]();
double newTempVal = 22.0;
double newHumVal = 70.0;
[Link](newTempVal, newHumVal);
cout << "\nWeather Data after call by value update:" << endl;
[Link]()
newTempRef = 28.0;
newHumRef = 65.0;
cout << "\nTrying to change newTempRef and newHumRef after call by reference:" << endl;
[Link]();
return 0;
}
OUTPUT:-

22
VANSHAM MAHAJAN 23124117

You might also like