0% found this document useful (0 votes)
1 views

OOP Problem Statements

The document outlines a series of practical programming problems in C++ covering various concepts such as arithmetic operations, classes, inheritance, polymorphism, and operator overloading. Each problem includes specific requirements for creating programs that demonstrate the use of different programming techniques, including user input, mathematical calculations, and class design. The problems are structured to progressively build on complexity, from basic operations to more advanced concepts like friend functions and inheritance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

OOP Problem Statements

The document outlines a series of practical programming problems in C++ covering various concepts such as arithmetic operations, classes, inheritance, polymorphism, and operator overloading. Each problem includes specific requirements for creating programs that demonstrate the use of different programming techniques, including user input, mathematical calculations, and class design. The problems are structured to progressively build on complexity, from basic operations to more advanced concepts like friend functions and inheritance.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PRACTICAL 1

Problem 1: Simple Arithmetic Operations

Write a C++ program that takes two integers as input from the user and performs the
following operations:

1. Addition

2. Subtraction

3. Multiplication

4. Division (integer division)

5. Modulo (remainder after division)

Problem 2: Increment and Decrement Operators

Write a C++ program that demonstrates the use of pre-increment (++i), post-increment
(i++), pre-decrement (--i), and post-decrement (i--) operators on an integer variable. The
program should print the results before and after each operation.

Problem 3: Relational and Logical Operators

Write a C++ program that accepts two integers from the user. The program should check
the following conditions using relational and logical operators:

1. Whether the first number is greater than the second.

2. Whether the first number is equal to the second.

3. Whether both numbers are either greater than 10 or less than 20.

Problem 4: Calculate Compound Interest

Write a C++ program that calculates the compound interest on a principal amount. The
program should use the following formula for compound interest:
Where:

● A is the amount of money accumulated after t years, including interest.

● P is the principal amount.

● r is the annual interest rate (in percentage).

● t is the number of years the money is invested for.

The program should ask for the principal amount, rate of interest, and time period, then
compute and display the final amount and the interest.

Problem 5: Calculate the Area of a Triangle Using Heron's Formula

Problem 5 (Area of a Triangle using Heron's Formula) involves relational operators to


verify whether the given sides form a valid triangle and uses arithmetic and square root
functions to calculate the area.

Write a C++ program to calculate the area of a triangle given the lengths of its three
sides using Heron's formula:

Where:

● s is the semi-perimeter of the triangle.

● a, b, and c are the lengths of the sides of the triangle.

The area is then given by:

The program should take the lengths of the sides as input, compute the area, and print
the result. If the sides do not form a valid triangle, print an error message.
Problem 6: Matrix Multiplication

Write a C++ program that multiplies two matrices. The program should:

1. Take the dimensions of two matrices (A and B).

2. Input the elements of both matrices.

3. Multiply the matrices and display the result.

The program should ensure that the multiplication is possible by checking if the number
of columns in the first matrix is equal to the number of rows in the second matrix.
PRACTICAL 2

Triangle Type Determination


Write a program that takes three sides of a triangle as input and determines the type of
triangle:

● Equilateral (all sides are equal)

● Isosceles (two sides are equal)

● Scalene (all sides are different)


Check if the given sides can form a triangle before determining its type.

Eligibility for Admission


A student is eligible for admission if:

● The student's age is above 18, and

The student has scored more than 60% in Mathematics, Physics, and Chemistry.
Write a program that takes age and marks in these subjects as input and determines if
the student is eligible

5. Simple Menu-Based Program


Write a program that displays the following menu:

1. Check Even or Odd

2. Find Maximum of Two Numbers

3. Calculate Square of a Number

4. Exit

Use a switch statement to implement each option.


Electricity Bill Calculator
Write a program that calculates the electricity bill based on units consumed:

● First 100 units: $0.50 per unit

● Next 200 units: $0.75 per unit

● Beyond 300 units: $1.20 per unit


Implement the solution using a switch statement for range-based logic and an if-
else ladder to apply unit limits.

Leap Year Checker


Create a program that checks if a given year is a leap year. Use nested if statements to
handle:

● A year is a leap year if it is divisible by 4 but not divisible by 100, or it is divisible


by 400.
PRACTICAL 3

1. Rectangle Area Calculation

Create a class Rectangle with attributes for length and width. Implement methods to
set the dimensions, calculate the area, and display the area.

2. Calculator for Two Numbers

Design a class Calculator with methods to add, subtract, multiply, and divide two
numbers. Allow the user to input the numbers and choose the operation.

3. Student Grade Management

Create a class Student to store a student's name, roll number, and marks in three
subjects. Implement a method to calculate the total marks and display the student's
details along with the total marks.

4. Circle Operations

Create a class Circle with an attribute for the radius. Implement methods to calculate
the circumference and area of the circle and display the results.

5. Book Information

Design a class Book to store the title, author, and price of a book. Implement methods
to set the details, display the details, and calculate a discounted price (e.g., 10% off).

6. A software application requires a class to represent a student with attributes like


name, roll number, and grades. However, het the details and print their details.

7. Design a class BankAccount to model a banking system. The class should have
attributes like account number, account holder's name, and balance. Implement
methods to perform operations such as deposit, withdraw, and check balance,
ensuring proper handling of invalid transactions (e.g., withdrawing more than the
current balance).
PRACTICAL 4

Q1. Develop a program that performs mathematical operations using function


overloading. Implement multiple overloaded versions of a function compute() that can:

● Compute the power of a number (base and exponent, both integers).

● Compute the power of a number (base as double and exponent as an integer).

● Compute the factorial of an integer.

● Compute the greatest common divisor (GCD) of two integers.

Ensure the program prompts the user for input, determines which function to call based
on the arguments provided, and displays the correct results.

Q.2 Develop a C++ program that demonstrates runtime polymorphism using virtual
functions in an inheritance-based shape hierarchy..Create a base class Shape with the
following:

o A pure virtual function calculateArea() that will be overridden by derived


classes.

o A virtual function display() to print shape-specific information.

1. Derive the following classes from Shape:

o Rectangle: Accepts length and width, overrides calculateArea().

o Circle: Accepts radius, overrides calculateArea().

o Triangle: Accepts base and height, overrides calculateArea().

2. Implement dynamic method binding using pointers:

o Create an array of Shape* pointers to store objects of different derived


classes.

o Use dynamic binding to call calculateArea() and display() through base


class pointers.

3. Allow user input for shape dimensions and display the calculated areas
dynamically.
PRACTICAL 5

Complex Number Operations (Parameterized Constructor & Operator Overloading)

Problem Statement:
Design a Complex class with:

● real (double)

● imag (double)

The class should have:

● A parameterized constructor to initialize the real and imaginary parts.

● A default constructor that sets both parts to 0.0.

● A member function to display the complex number in a + bi format.

● An overloaded + operator to add two complex numbers.


PRACTICAL 6

To demonstrate the concept of friend functions and friend classes in C++, where a
function or class is given access to private and protected members of another class
without being a member of that class.

Problem Description:

1. Create a class Rectangle with private data members:

○ length (integer)

○ width (integer)

2. Implement a friend function calculateArea that takes an object of Rectangle as a


parameter and calculates the area of the rectangle.

3. Create another class RectangleOperations which needs access to the private


members of Rectangle.

○ Declare RectangleOperations as a friend class of Rectangle.

○ Implement a function doubleDimensions() inside RectangleOperations,


which doubles the values of length and width of a Rectangle object.

Constraints:

● The friend function should be non-member but have access to private members.

● The friend class should be able to modify the private members of Rectangle.

● The main function should demonstrate the usage of both the friend function and
friend class.

Expected Output:

● The program should display the original and modified dimensions of the
rectangle.

● It should correctly compute and display the area using the friend function.
Problem Description:

Develop a banking system with the following classes:

1. BankAccount Class (Main Class)

● Private Data Members:

○ accountNumber (integer)

○ accountHolderName (string)

○ balance (double)

● Public Member Functions:

○ Constructor to initialize account details.

○ Function displayAccountDetails() to print public details.

● Friend Function:

○ void displayBalance(const BankAccount&) → Allows an external function


to access and display the private balance of a bank account.

● Friend Class:

○ BankManager → This class has full access to BankAccount's private


members.

2. Transaction Class

● Private Data Members:

○ transactionID (integer)

○ transactionAmount (double)

○ transactionType (string: "Deposit" or "Withdraw")

● Friend Function of BankAccount:

○ void processTransaction(BankAccount&, Transaction&) → This function


modifies the balance of BankAccount based on the transaction type.
3. BankManager Class (Friend of BankAccount)

● The BankManager is responsible for:

○ Modifying account balance.

○ Accessing and changing the account holder’s name.

○ Closing an account (resetting details).

Functional Requirements:

1. Create a Bank Account

○ The user provides account details (account number, name, and initial
balance).

○ The account is stored in an object of BankAccount.

2. Process Transactions (Friend Function Usage)

○ processTransaction() can:

■ Add money to the balance (Deposit).

■ Deduct money (Withdraw) if the balance is sufficient.

3. View Account Details (Limited Access)

○ The public displayAccountDetails() function shows only account number


and holder name.

○ The friend function displayBalance() allows the private balance to be


displayed.

4. Bank Manager Privileges (Friend Class Usage)

○ The BankManager class can:

■ Change the account holder's name.

■ Reset the balance (for account closure).


■ Manually adjust the balance (e.g., apply penalties or add
bonuses).

Constraints:

● Encapsulation: Direct access to BankAccount’s private data from outside is


prohibited.

● Friend Function Control: Only specific friend functions can modify private data.

● Friend Class Security: Only BankManager can alter account details.

Expected Output:

1. Display account details (without balance).

2. Use displayBalance() to show the balance (demonstrating a friend function).

3. Perform deposits and withdrawals using processTransaction().

4. Use BankManager to change the account holder’s name and reset the account.

Print updated details after modifications.


PRACTICAL 7

Problem 1: Employee Management System (Parameterized & Copy Constructor)

Problem Statement:
Create a class Employee with the following attributes:

● id (integer)

● name (string)

● salary (double)

The class should include:

● A parameterized constructor to initialize these attributes.

● A copy constructor that copies an existing employee’s details into a new object.

● A member function display() to print the employee details.

Write a program that demonstrates the use of both constructors by creating an


employee object and then copying it into another object.

Problem 2: Using a Parameterized Constructor

Problem Statement:
Design a Rectangle class with the following attributes:

● length (float)

● width (float)

The class should include:

● A parameterized constructor to initialize these attributes.

● A member function area() that calculates and returns the area of the rectangle.

Write a program that creates a Rectangle object using the parameterized constructor
and displays its area.
Problem 3: Complex Number Operations (Parameterized Constructor & Operator
Overloading)

Problem Statement:
Design a Complex class with:

● real (double)

● imag (double)

The class should have:

● A parameterized constructor to initialize the real and imaginary parts.

● A default constructor that sets both parts to 0.0.

● A member function to display the complex number in a + bi format.

● An overloaded + operator to add two complex numbers.

● An overloaded * operator to multiply two complex numbers.

Write a program that takes two complex numbers as input, performs addition and
multiplication, and displays the results.

Problem 4: Inventory Management System (Constructor Overloading & Destructor)

Problem Statement:
Develop an Item class that has:

● itemCode (string)

● itemName (string)

● price (double)

● quantity (integer)

The class should have:

● A default constructor to initialize itemCode = "N/A", itemName = "N/A", price =


0.0, and quantity = 0.

● A parameterized constructor that allows setting all attributes.

● A destructor that prints a message when an object is destroyed.

● A member function display() to show item details.


PRACTICAL 8

Problem Statement: Single Inheritance

Create a program that demonstrates single inheritance in object-oriented programming.

Requirements:

1. Define a base class called Person with the following attributes and methods:

o Attributes: name and age

o Method: display_info() – Prints the name and age of the person.

2. Define a derived class called Student that inherits from Person. It should have:

o Additional attribute: student_id

o Method: display_student_info() – Prints the student ID along with the


person's details using display_info().

Create an object of the Student class, assign values to all attributes, and call the
methods to display the details.

Problem Statement: Employee Management System Using Single Inheritance

Objective:

Develop a program to manage employee details using single inheritance. The system
should include basic employee attributes and extend functionality for specialized
employees.

Requirements:

1. Create a base class Employee with the following:

o Attributes:

▪ name (Employee's name)

▪ emp_id (Employee ID)

▪ salary (Basic salary)

o Method:

▪ display_details() – Displays the employee's details.

2. Create a derived class Manager that inherits from Employee and includes:
o Additional attributes:

▪ department (Department the manager oversees)

▪ bonus (Performance-based bonus)

o Method:

▪ calculate_total_salary() – Computes the total salary including the


bonus.

▪ Override display_details() to include department and total salary.

3. Create another derived class Developer that inherits from Employee and
includes:

o Additional attributes:

▪ programming_language (Primary language of the developer)

▪ project (Current assigned project)

o Override display_details() to show developer-specific details.

4. Implementation:

o Create objects of both Manager and Developer classes.

o Assign values and display their details.

Complex Problem Statement: Single Inheritance with Extended Functionality

Develop a program that demonstrates single inheritance with advanced features such
as method overriding, additional attributes, and multiple operations. The scenario
involves a base class representing a general Bank Account and a derived class for a
Savings Account with extra functionalities.

Requirements:

1. Base Class: BankAccount

o Attributes:

▪ account_number (unique identifier)

▪ account_holder (name of the account holder)

▪ balance (current balance)

o Methods:
▪ deposit(amount): Increases the balance by the specified amount.

▪ withdraw(amount): Decreases the balance by the specified


amount if sufficient funds exist; otherwise, print an error message.

▪ display_account_info(): Displays the account number, holder


name, and current balance.

2. Derived Class: SavingsAccount (Inherits from BankAccount)

o Additional Attribute:

▪ interest_rate (annual interest rate in percentage)

o Additional Methods:

▪ calculate_interest(years): Calculates and returns the interest


accumulated over a given number of years based on the current
balance and the interest rate.

▪ Method Overriding: Override the withdraw(amount) method to


include a penalty fee (e.g., deduct a fixed amount or percentage) if
the withdrawal amount exceeds a specified limit per month. The
overridden method should first check if the monthly withdrawal
limit has been exceeded before processing the withdrawal.

3. Implementation Details:

o Instantiate a SavingsAccount object with sample values.

o Demonstrate the following operations:

▪ Deposit funds into the account.

▪ Attempt multiple withdrawals to test the penalty mechanism for


exceeding the withdrawal limit.

▪ Display the account information after transactions.

▪ Calculate and display the projected interest for a given period


(e.g., 3 years).

o Ensure proper error handling and informative messages for failed


operations (like insufficient funds or exceeding the withdrawal limit).
Problem Statement: Multilevel Inheritance in C++

Objective:

Implement a multilevel inheritance structure in C++ to demonstrate how derived


classes inherit features from a base class through intermediate classes.

Problem Description:

Create a C++ program that models the following hierarchy:

1. Class Person (Base Class)

2.

o Data members: name, age

o Member functions: setPersonDetails(), displayPersonDetails()

3. Class Student (Derived from Person)

o Additional data members: studentID, course

o Additional member functions: setStudentDetails(),


displayStudentDetails()

4. Class GraduateStudent (Derived from Student)

o Additional data members: researchTopic, advisorName

o Additional member functions: setGraduateDetails(),


displayGraduateDetails()

Requirements:

● Use multilevel inheritance (Person → Student → GraduateStudent).

● Implement setter and getter functions to input and display details.

● Use constructors to initialize class members.

● Demonstrate the functionality by creating an object of GraduateStudent and


displaying details.
 Create a class in C++ to represent a rectangle. The class should encapsulate the
rectangle's width and height. Users should be able to:

 Set the width and height of the rectangle.

 Get the width and height of the rectangle.

 Calculate and retrieve the area of the rectangle.

Develop a class in C++ to model a simple bank account that demonstrates the concept
of data encapsulation. The class should encapsulate the account's details such as
account number, account holder's name, and account balance. Users should be able
to:

1. Create an account with an initial balance.

2. Deposit funds into the account.

3. Withdraw funds from the account (only if there are sufficient funds).

4. Check the account balance.

The internal details of the account should not be accessible directly from outside the
class. Instead, users should interact with the account through public member
functions.
PRACTICAL 9

Q.2 Develop a C++ program that demonstrates runtime polymorphism using virtual
functions in an inheritance-based shape hierarchy..Create a base class Shape with the
following:

o A pure virtual function calculateArea() that will be overridden by derived


classes.

o A virtual function display() to print shape-specific information.

4. Derive the following classes from Shape:

o Rectangle: Accepts length and width, overrides calculateArea().

o Circle: Accepts radius, overrides calculateArea().

o Triangle: Accepts base and height, overrides calculateArea().

5. Implement dynamic method binding using pointers:

o Create an array of Shape* pointers to store objects of different derived


classes.

o Use dynamic binding to call calculateArea() and display() through base


class pointers.

6. Allow user input for shape dimensions and display the calculated areas
dynamically.

A software development team is working on an Employee Management System for a


company. The company has different types of employees, such as Managers,
Developers, and Interns. All employees share some common attributes like name,
employee ID, and salary, but each type of employee has specific attributes and
functionalities.

Your task is to implement a hierarchical inheritance structure in C++ as follows:

● Create a base class Employee with common attributes and a function to display
basic employee details.

● Create three derived classes:

1. Manager - Includes additional attributes such as the department name


and a function to display managerial details.
2. Developer - Includes attributes like programming language expertise and
a function to display developer-specific details.

3. Intern - Includes attributes such as duration of internship and a function


to display intern-related details.

Each derived class should override the display function to show both common and
specific details. The program should allow creating instances of each class and
displaying their information.
PRACTICAL 10

Problem Statement: Exception Handling in a Banking System

Objective

Design and implement an exception-handling mechanism for a simple banking system.


The system should handle various types of exceptions that may occur during banking
operations such as deposits, withdrawals, and account management.

Requirements

1. Create a Bank Account Class

o Attributes: account_number, account_holder, balance

o Methods: deposit(amount), withdraw(amount), get_balance()

2. Handle Exceptions for the Following Scenarios:

o InsufficientBalanceException: Raised when a withdrawal request exceeds


the available balance.

o InvalidAmountException: Raised when a user attempts to deposit or


withdraw a non-positive amount.

o AccountNotFoundException: Raised when attempting to access an


account that does not exist.

3. Implementation Guidelines:

o Use try-except blocks to catch and handle exceptions appropriately.

o Provide meaningful error messages to guide the user.

o Ensure the system does not crash due to invalid operations.

4. Example Test Cases:

o Attempt to withdraw more money than the current balance.

o Try to deposit a negative or zero amount.

o Attempt to access an invalid account.


Problem Statement: Exception Handling in a File Management System

Objective

Design and implement a file management system that properly handles exceptions
during file operations such as reading, writing, and deleting files.

Requirements

1. Implement a File Manager Class

o Methods:

▪ read_file(filename): Reads the contents of a file.

▪ write_file(filename, content): Writes data to a file.

▪ delete_file(filename): Deletes a file.

2. Handle Exceptions for the Following Scenarios:

o FileNotFoundError: Raised when trying to read or delete a file that does


not exist.

o PermissionError: Raised when there is insufficient permission to access


or modify a file.

o IsADirectoryError: Raised when trying to perform file operations on a


directory instead of a file.

o IOError: Handle any other unforeseen file I/O errors.

3. Implementation Guidelines:

o Use try-except blocks to catch and handle exceptions appropriately.

o Provide user-friendly error messages for better debugging.

o Ensure the system does not crash due to unexpected file errors.

4. Example Test Cases:

o Try reading a non-existent file.

o Attempt writing to a read-only file.

o Try deleting a directory instead of a file.


Problem Statement: Exception Handling in an E-Commerce Order Processing System

Objective

Develop an exception-handling mechanism for an e-commerce system that processes


customer orders while handling various errors that may occur during transactions.

Requirements

1. Implement an Order Processing System

o Classes:

▪ Product: Represents a product with attributes like product_id,


name, price, and stock_quantity.

▪ Order: Represents an order with methods like


add_to_cart(product, quantity), remove_from_cart(product), and
checkout().

2. Handle Exceptions for the Following Scenarios:

o OutOfStockException: Raised when a customer tries to purchase more


items than are available in stock.

o InvalidQuantityException: Raised when the user tries to add a negative or


zero quantity of a product.

o PaymentProcessingException: Raised when there is an issue with


payment processing (e.g., insufficient funds, invalid card details).

o ProductNotFoundException: Raised when attempting to order a product


that does not exist.

3. Implementation Guidelines:

o Use try-except blocks to catch and handle exceptions.

o Display appropriate error messages to the user.

o Ensure the system can continue running smoothly even if an error occurs.

4. Example Test Cases:

o Attempt to purchase a product that is out of stock.

o Try to add an invalid quantity of a product to the cart.

o Simulate a failed payment transaction.

o Attempt to order a non-existent product.


OTHER PROGRAMS:

Problem:

Create a function template in C++ that takes two values of any data type and swaps
them.

Requirements:

1. Implement a function template swapValues that:

o Takes two values by reference.

o Swaps their values.

2. Test the function with:

o Integers

o Floating-point numbers

o Characters

Problem Statement: Advanced Function Template in C++

Problem:

Create a function template in C++ that can work with multiple data types and perform
an advanced operation. Specifically, implement a function template named
findMaxWithIndex that:

1. Accepts an array of elements of any data type.

2. Accepts the size of the array.

3. Finds and returns both:

o The maximum element in the array.

o The index of the maximum element in the array.

Requirements:

1. Implement a function template findMaxWithIndex that:

o Works with different data types (int, double, char, etc.).

o Returns a pair containing the maximum element and its index.

2. Test the function with:

o An integer array.
o A floating-point array.

o A character array.

Problem Statement: Class Template in C++

Problem:

Create a class template in C++ that can store and perform basic operations on two
values of the same data type. The class should allow users to:

1. Store two values of a generic type.

2. Retrieve the stored values.

3. Find the maximum of the two values.

Requirements:

Implement a class template Pair that:

Accepts two values of a generic type.

Provides methods to:

Set values.

Get values.

Find the maximum value.

Test the class with:

Integers

Floating-point numbers

Characters

Declare variables of different data types and assign values to them. Print these
values.

Write a program to take two numbers as input and perform arithmetic operations.

Write a C++ program that demonstrates


the use of pre-increment (++i),

post-increment (i++), pre-decrement (--i),

and post-decrement (i--) operators on an integer variable.

The program should print the results before and after each operation.

Problem 1: Single-Dimensional Array - Sum of Elements

Problem Statement:
Write a program in C++ to read 5 integers from the user, store them in an array, and
calculate the sum of all the elements using a for loop.

Problem 2: Multi-Dimensional Array - Matrix Addition

Problem Statement:
Write a program in C++ to add two 2x2 matrices. Use a two-dimensional array and for
loops to compute the result.

Problem 3: Array Reversal

Problem Statement:
Write a C++ program to reverse the elements of a single-dimensional array using a for
loop.

Problem 4: Multi-Dimensional Array - Transpose of a Matrix

Problem Statement:
Write a program in C++ to find the transpose of a 3x3 matrix using for loops.

Write a program that takes the number of a month (1-12) as input and outputs the name
of the month and its corresponding season using a switch statement.
Write a program that acts as a simple calculator. The user provides two numbers and an
operator (+, -, *, /, %) as input. Use a switch statement to perform the corresponding
operation. Handle division by zero and invalid operators gracefully.

Create a menu-driven calculator using a switch-case statement that supports addition,


subtraction, multiplication, division, and modulo operations. The user should input two
numbers and select an operation. If division or modulo is chosen and the divisor is zero,
display an error message. Otherwise, perform the chosen operation and display the
result.

You might also like