0% found this document useful (0 votes)
63 views16 pages

C++ Object-Oriented Programming Assignments

The document contains an assignment submission for an "Object Oriented Programming" course. It includes 7 programming problems/questions to be solved using C++ classes and objects. The problems cover concepts like creating classes for Points, BankAccounts, calculating electricity bills, finding the largest of 3 numbers, checking student exam pass/fail, calculating properties of geometric shapes, and answering questions about a Seminar class.

Uploaded by

Muhammad Irfan
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)
63 views16 pages

C++ Object-Oriented Programming Assignments

The document contains an assignment submission for an "Object Oriented Programming" course. It includes 7 programming problems/questions to be solved using C++ classes and objects. The problems cover concepts like creating classes for Points, BankAccounts, calculating electricity bills, finding the largest of 3 numbers, checking student exam pass/fail, calculating properties of geometric shapes, and answering questions about a Seminar class.

Uploaded by

Muhammad Irfan
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

“Object Oriented Programming”

Assignment # 1
Date of Submission:
28th September 2023

Prepared For:
Ma’am Asma Bibi

Section:
BEE-3C

Prepared by:

NAME REGISTRATION NUMBER


Muhammad Abdullah CIIT/FA22-BEE-125/ISB

COMSATS UNIVERSITY ISLAMABAD.


1. Create a class called Point that has two data members: x‐ and y‐coordinates of the
point. Provide a no‐ argument and a 2‐argument constructor. Provide separate get
and set functions for the each of the data members i.e. getX, getY, setX, setY. The
getter functions should return the corresponding values to the calling function.
Provide a display method to display the point in (x, y) format. Make appropriate
functions const.

#include <iostream>
using namespace std;

class Point
{
private:
double x;
double y;

public:
Point()
{
x = 0.0;
y = 0.0;
}
Point(double A, double B)
{
x =A;
y = B;
}
double getX() const
{
return x;
}
double getY() const
{
return y;
}
void setX(double newX)
{
x = newX;
}
void setY(double newY)
{
y = newY;
}
void display()

COMSATS UNIVERSITY ISLAMABAD.


{
cout << "(" << x << ", " << y << ")"<<endl;
}
};
int main()
{
Point p1;
Point p2(3.5,2.0);
cout << "p1 coordinates: (" << [Link]() << ", " << [Link]() << ")" <<endl;
cout << "p2 coordinates: "<<endl;
[Link]();
[Link](4.0);
[Link](9.5);
cout << "Updated p1 coordinates: "<<endl;
[Link]();
return 0;
}

2. Create a class called BankAccount that models a checking account at a bank. The
program creates an account with an opening balance, displays the balance, makes a
deposit and a withdrawal, and then displays the new balance. Note in withdrawal
function, if balance is below Rs. 500 then display message showing insufficient balance
otherwise allow withdrawal.

#include <iostream>
using namespace std;

class BankAccount {
private:
double balance;

public:
BankAccount(double initialBalance)
{
balance = 10500;
}
void displayBalance() const
{
cout << "Current Balance: Rs. " << balance << endl;
}
void deposit(double amount)
{
if (amount > 0) {
balance += amount;
cout << "Deposited Rs. " << amount << endl;

COMSATS UNIVERSITY ISLAMABAD.


} else {
cout << "Invalid deposit amount." <<endl;
}
}
void withdraw(double amount) {
if (amount > 0) {
if (balance - amount >= 500) {
balance -= amount;
cout << "Withdrawn Rs. " << amount << endl;
} else {
cout << "Insufficient balance. Minimum balance of Rs. 500 required." <<endl;
}
} else {
cout << "Invalid withdrawal amount." << endl;
}
}
};

int main() {

BankAccount account(1000.0);
[Link]();
[Link](500.0);
[Link]();
[Link](800.0);
[Link]();
[Link](700.0);
[Link]();
return 0;
}

COMSATS UNIVERSITY ISLAMABAD.


3. An electricity board charges the following rates to domestic users ti discourage large
consumption of energy: For the first 100 units - 60P per unit For next 200 units - 80P
per unit Beyond 300 units - 90P per unit All users are charged a minimum of Rs.50.00.
if the total amount is more than Rs.300.00 than an additional surcharge of 15% is
added Write a C++ program to read the names of users and number of units
consumed and print out the charges with names.

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

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

int main() {
int numUsers;
cout << "Enter the number of users: ";
cin >> numUsers;

for (int i = 0; i < numUsers; i++) {


string userName;
int unitsConsumed;

cout << "Enter the name of user " << i + 1 << ": ";
cin >> userName;
cout << "Enter the number of units consumed by " << userName << ": ";
cin >> unitsConsumed;

double charges = 0.0;

if (unitsConsumed <= 100) {


charges = 0.6 * unitsConsumed;
} else if (unitsConsumed <= 300) {
charges = (0.6 * 100) + (0.8 * (unitsConsumed - 100));
} else {
charges = (0.6 * 100) + (0.8 * 200) + (0.9 * (unitsConsumed - 300));
}

if (charges < 50.0)


{
charges = 50.0;
}

COMSATS UNIVERSITY ISLAMABAD.


if (charges > 300.0) {
charges += 0.15 * charges;
}

cout << "Charges for " << userName << ": Rs. " << charges << endl;
}

return 0;
}

4. Develop a C++ program find the largest among three different numbers entered by
user.

#include <iostream>
using namespace std;

int main()
{
double num1, num2, num3;
cout << "Enter three different numbers: ";
cin >> num1 >> num2 >> num3;
if (num1 != num2 && num1 != num3 && num2 != num3)
{
if (num1 > num2 && num1 > num3)
{
cout << "The largest number is: " << num1 << endl;
}
else if (num2 > num1 && num2 > num3)
{
cout << "The largest number is: " << num2 << endl;
}
else
{
cout << "The largest number is: " << num3 << endl;
}
}
return 0;
}

COMSATS UNIVERSITY ISLAMABAD.


5. Using a C++ program check whether a student passed the exam or not based on total
mark which shall be above 40%.

#include <iostream>
using namespace std;

int main()
{
double totalMarks, obtainedMarks;
cout << "Enter the total marks: ";
cin >> totalMarks;
cout << "Enter the obtained marks: ";
cin >> obtainedMarks;

double passing_marks = 0.4 * totalMarks;

if (obtainedMarks >= passing_marks)


{
cout << "Congratulations! You have passed the exam." << endl;
}
else
{
cout << "Sorry, you did not pass the exam." << endl;
}
return 0;
}

COMSATS UNIVERSITY ISLAMABAD.


6. Write program using class Geometry. The program should ask the user for length and
width if the length and width both are same then it should call square function to
calculate its area and parameter otherwise it should call rectangle function to
calculate the area and parameter of the rectangle.

#include <iostream>
using namespace std;

class Geometry {
private:
double length;
double width;

public:

Geometry(double l, double w)
{
length = l;
width = w;
}

double squareArea()
{
return length * length;
}
double squarePerimeter()
{
return 4 * length;
}

double rectangleArea()
{
return length * width;
}
double rectanglePerimeter()
{
return 2 * (length + width);
}
};

int main()
{
double length, width;
cout << "Enter the length: ";

COMSATS UNIVERSITY ISLAMABAD.


cin >> length;
cout << "Enter the width: ";
cin >> width;

Geometry geometry(length, width);

if (length == width)
{
cout << "It's a square." << endl;
cout << "Area: " << [Link]() << endl;
cout << "Perimeter: " << [Link]() << endl;
}
else
{
cout << "It's a rectangle." << endl;
cout << "Area: " << [Link]() << endl;
cout << "Perimeter: " << [Link]() << endl;
}
return 0;
}

7. Answer the questions (i) and (iii) after going through the following class:
class Seminar
{
int time;
public:
Seminar() //Function 1
{
time = 30;
cout << "Seminar starts now" << endl;
}
void lecture() //Function 2
{
cout << "Lectures in the seminar on" << endl;
}
Seminar(int duration) //Function 3

COMSATS UNIVERSITY ISLAMABAD.


{
time = duration;
cout << "Seminar starts now" << endl;
}
~Seminar() //Function 4
{
cout << "Thanks" << endl;
}
};

a. Write statements in C++ that would execute Function 1 and Function 3 of class
Seminar.

Seminar seminar1;
Seminar seminar2(45);

b. In Object Oriented Programming, what is Function 4 referred as and when does it


get invoked/called?

Function 4 is referred as a destructor. It gets invoked automatically when an object of the


class goes out of scope.

c. In Object Oriented Programming, which concept is illustrated by Function 1 and


Function 3 together?

The concept which is illustrated by Function 1 and Function 3 is Constructor


Overloading. It allows a class to have multiple constructors with different parameters.

8. Answer the questions after going through the following class:


class Test{
char paper[20];
int marks;

public:
Test () // Function 1
{
strcpy (paper, "Computer");

COMSATS UNIVERSITY ISLAMABAD.


marks = 0;
}
Test (char p[]) // Function 2
{
strcpy(paper, p);
marks = 0;
}
Test (int m) // Function 3
{
strcpy(paper,"Computer");
marks = m;
}
Test (char p[], int m) // Function 4
{
strcpy (paper, p);
marks = m;
}
};
a. Write statements in C++ that would execute Function 1, Function 2, Function 3 and
Function 4 of class Test.

Test test1
Test test2("Biology");
Test test3(75);
Test test4("Maths", 92);

b. Which feature of Object-Oriented Programming is demonstrated using Function 1,


Function 2, Function 3 and Function 4 together in the above class Test?

Constructor Overloading.

COMSATS UNIVERSITY ISLAMABAD.


9. Answer the questions (i) and (ii) after going through the following class:

class Sample
{
private:
int x;
double y;
public :
Sample(); //Constructor 1
Sample(int); //Constructor 2
Sample(int, int); //Constructor 3
Sample(int, double); //Constructor 4
};
a. Write the definition of the constructor 1 so that the private member variables are
initialized to 0.

Sample::Sample()
{
x = 0;
y = 0.0;
}

b. Write the definition of the constructor 2 so that the private member variable x is
initialized according to the value of the parameter, and the private member variable
y is initialized to 0.

Sample::Sample(int value)
{
x = value;
y = 0.0;
}

COMSATS UNIVERSITY ISLAMABAD.


c. Write the definition of the constructors 3 and 4 so that the private
member variables are initialized according to the values of the parameters.

For Constructor 3: -

Sample::Sample(int value1, int value2)


{
x = value1;
y = value2;
}

For Constructor 4: -

Sample::Sample(int value1, int value2)


{
x = value1;
y = value2;
}

10. Find the output of given Program and also find error if it has. Write down description
of every statement having //.
#include<iostream>//
using namespace std ;//

class Box //
{
public : //
double length ; //
double breadth ; //
double height ; //
};
int main (void) //
{
Box Box1 ; //
Box Box2 ; //
double volume = 0.0 ; //
[Link] = 18.0 ; //
[Link] = 78.0 ; //
[Link] = 24.0 ; //
[Link] = [Link] − 10 ; //
[Link] = [Link] / 2 . 0 ; //
[Link] = 0.2 5∗ [Link] ; //
volume = [Link] ∗ Box1 . length ∗ Box1 . breadth ; //

COMSATS UNIVERSITY ISLAMABAD.


cout << endl //

<< "Volume o f Box1 = " << volume ;


cou t << endl
<< " Box2 has si d e s which t o t a l "
<< Box2 . hei gh t + Box2 . len g th + Box2 . bread th
<< " in che s . " ;//
cout << endl // Display the si z e o f a box in memory
<< "A Box o b j e c t occupie s "
<< s i z e o f Box1 << " by te s . " ; cou t <<endl ;//
return 0 ;
}

Errors in Code

COMSATS UNIVERSITY ISLAMABAD.


Correct Code

OUTPUT

COMSATS UNIVERSITY ISLAMABAD.


Description:

1. #include <iostream>: Includes the header file for input and output stream handling.
2. using namespace std;: Specifies that the program will use the std namespace.
3. class Box {};: Defines a class named Box with three double precision member variables:
length, breadth, and height.
4. int main() {: Start of the main function.
5. Box Box1; and Box Box2;: Declares two objects of the Box class named Box1 and Box2.
6. double volume = 0.0;: Declares a double variable volume and initializes it to 0.0.
7. Setting values for the dimensions of Box1 using the dot operator.
8. Calculations to set values for the dimensions of Box2.
9. Calculation of the volume of Box1.
10. cout << endl << "Volume of Box1 = " << volume;: Outputs the volume of Box1.
11. cout << endl << "Box2 has sides which total " ...: Outputs the total of sides of Box2.
12. cout << endl << "A Box object occupies " ...: Outputs the size of Box1 in bytes.
13. return 0;: Indicates the end of the main function.

COMSATS UNIVERSITY ISLAMABAD.

Common questions

Powered by AI

The program calculates charges based on unit consumption, applying conditional logic to apply escalating rates for units consumed beyond certain thresholds and an additional surcharge if charges exceed Rs. 300. Techniques such as conditional statements (`if-else`) ensure different tiers and conditions are correctly applied .

Constructor Overloading allows the class `Seminar` to be instantiated with different initial states without creating separate methods for initialization. It provides the flexibility to instantiate objects with or without parameters, promoting cleaner and more intuitive code management by consolidating initialization logic within the constructors .

The `BankAccount` class manages transactions through methods for deposits and withdrawals while ensuring constraints like a minimum balance of Rs. 500 before allowing a withdrawal. Robustness can be improved by adding data validation for initial balance, as the current setup initializes all accounts with a fixed balance regardless of input. Additionally, implementing exception handling for invalid operations would improve usability .

The logic error in the `Box` class code occurs during the calculation of `Box2` dimensions: `Box2.breadth = 0.25 * Box1.length;` and possibly integer division in dimension computations. This may lead to incorrect breadth calculation due to precedence issues without clear parenthesis use. Proper data type usage and explicit expressions should be applied for accurate arithmetic .

The `Sample` class uses various constructors to initialize its data members. Constructor 1 uses default values, while Constructor 2 initializes `x` with a parameter and defaults `y`. Constructors 3 and 4 allow full custom initialization. This design caters to diverse use cases but may benefit from consistent use of member initializer lists for potentially improved performance and readability .

The `Geometry` class effectively encapsulates the properties required to calculate the area and perimeter of squares and rectangles. By delegating calculations to separate methods based on shape identification (i.e., matching length and width for squares), it maintains abstraction and encapsulation principles. However, polymorphic design could be added to handle shape type dynamically, improving scalability .

The `Point` class models a point in a 2D space with `x` and `y` coordinates, demonstrating encapsulation by keeping these coordinates private while providing public methods to access and modify them. The class offers a no-argument constructor for default point initialization and a two-argument constructor for custom initialization. It includes getter and setter methods for the coordinates, adhering to the concept of data hiding, and a `display` function for output representation .

Constructor Overloading in class `Test` allows multiple constructors with different parameters, enabling the instantiation of objects in various initial states. This feature benefits object-oriented design by enhancing flexibility and reducing the need for multiple initialization methods, ensuring consistent object setup regardless of the input scenario .

Function pointers could be used to dynamically select passing criteria based on exam type or context, enabling more flexible and reusable code. The current design is straightforward but may become cumbersome with additional complexity or varied criteria. Function pointers allow better abstraction and code modularity, reducing redundancy across similar checks .

The simple conditional expression used for determining pass/fail status increases code clarity by concisely outlining requirements and outcomes. The impact on performance is minimal given the straightforward comparison, but as conditions become more complex, maintaining clarity with comments or refactoring into separate functions or strategies might be necessary to prevent errors and ensure maintainability .

You might also like