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

xyz

The document contains C++ programming assignments for a Department of Information Technology course, including a banking system, a library management system, a student class with static members, and a student grade management system. Each section includes code implementations and example outputs for the respective functionalities. The assignments focus on object-oriented programming concepts such as classes, structures, member functions, and static data members.

Uploaded by

un67965
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

xyz

The document contains C++ programming assignments for a Department of Information Technology course, including a banking system, a library management system, a student class with static members, and a student grade management system. Each section includes code implementations and example outputs for the respective functionalities. The assignments focus on object-oriented programming concepts such as classes, structures, member functions, and static data members.

Uploaded by

un67965
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

DEPARTMENT OF INFORMATION

TECHNOLOGY (IT)
SESSION 2024-25

SEMESTER : 2

Submitted by :
Name : KSHEERA SAGAR SHIVANSH
Scholar No : 24U030057
Subject : OBJECT ORIENTED
PROGRAMMING
Q1) write a program to create a banking system using C++
1)create bank account structure - account holders name account number and balance
2)write functions deposit money & withdraw money & display account details and use switch case inside
do while loop and allow user to deposit /withdraw/view balance until they choose to exit

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

struct BankAccount
{
string name;
int accountNumber;
double balance;
};

void deposit(BankAccount &account, double amount)


{
if (amount > 0)
{
account.balance += amount;
cout << "\nAmount deposited successfully!\n";
}
else
{
cout << "\nInvalid deposit amount!\n";
}
}

void withdraw(BankAccount &account, double amount)


{
if (amount > 0 && amount <= account.balance)
{
account.balance -= amount;
cout << "\nAmount withdrawn successfully!\n";
}
else if (amount > account.balance)
{
cout << "\nInsufficient balance!\n";
}
else
{
cout << "\nInvalid withdrawal amount!\n";
}
}
void displayAccountDetails(const BankAccount &account)
{
cout << "\nAccount Holder's Name: " << account.name << endl;
cout << "Account Number: " << account.accountNumber << endl;
cout << "Account Balance: Rs" << account.balance << endl;
}

int main()
{
BankAccount account;
cout << "Enter account holder's name: ";
getline(cin, account.name);
cout << "Enter account number: ";
cin >> account.accountNumber;
cout << "Enter initial balance: ";
cin >> account.balance;

int choice;
double amount;

do
{
cout << "\n===== Banking System Menu =====" << endl;
cout << "1. Deposit Money" << endl;
cout << "2. Withdraw Money" << endl;
cout << "3. View Account Details" << endl;
cout << "4. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice)
{
case 1:
cout << "\nEnter amount to deposit: ";
cin >> amount;
deposit(account, amount);
break;

case 2:
cout << "\nEnter amount to withdraw: ";
cin >> amount;
withdraw(account, amount);
break;

case 3:
displayAccountDetails(account);
break;

case 4:
cout << "\nExiting the banking system. Thank you!\n";
break;

default:
cout << "\nInvalid choice. Please try again.\n";
}
} while (choice != 4);
return 0;
}

OUTPUT :
Enter account holder's name: SHIVANSH
Enter account number: 156982
Enter initial balance: 20000

===== Banking System Menu =====


1. Deposit Money
2. Withdraw Money
3. View Account Details
Enter your choice: 2

Enter amount to withdraw: 500

Amount withdrawn successfully!

===== Banking System Menu =====


1. Deposit Money
2. Withdraw Money
3. View Account Details
4. Exit
Enter your choice: 3

Account Holder's Name: SHIVANSH


Account Number: 156982
Account Balance: Rs19500

===== Banking System Menu =====


1. Deposit Money
2. Withdraw Money
3. View Account Details
4. Exit
Enter your choice: 4
Exiting the banking system. Thank you!

Q2) Create a C++ program to manage a library system using class.


Read all the instructions carefully and write your program accordingly.
Instructions:
1. Define Book class
a) class will include the following private variables:
bookID (Unique ID for each book). title (Title of the book),
authorName (one author's name), isissued (To check the status of the book, true issued, false availale),
issued To (Name of the person to whom the book is issued)
(Note: Multiple books can be there with same bookID, title and Author's name)
b) class will contain the following member functions:
(1) setBookDetails(arguments) (Initialize bookID, title, author, and set isissued to false by default)
(ii) addBook(no arguments) (To take user input from main function for book details and initialize the
book)
(iii) issueBook(person's name to whom the book will be issued) (To mark a book as issued if it is
available. If the book is already issued, display an appropriate message.)
(iv) returnBook(no arguments): (To mark
a book as returned if the book is not issued, display an appropriate message)
(v) displayDetails(no arguments): (To display all details of the book (ID, title, author, and status).
(Note: write the definition of all the functions outside the class)
In main function
(i) Create an array to store objects to simulate with multiple books. One object will contain details of one
book.
(ii) Use do while loop and switch case to perform multiple functions in a single run

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

class Book {
private:
int bookID;
string title;
string authorName;
bool isIssued;
string issuedTo;

public:
Book() {
bookID = 0;
title = "Untitled";
authorName = "Unknown";
isIssued = false;
issuedTo = "N/A";
}

void setBookDetails(int id, string t, string author) {


bookID = id;
title = t;
authorName = author;
isIssued = false;
issuedTo = "N/A";
}

void displayDetails() {
cout << "Book ID: " << bookID << endl;
cout << "Title: " << title << endl;
cout << "Author: " << authorName << endl;
cout << "Status: " << (isIssued ? "Issued to " + issuedTo : "Available")
<< endl;
}

void issueBook(string person) {


if (isIssued) {
cout << "Sorry, the book is already issued to " << issuedTo << endl;
} else {
isIssued = true;
issuedTo = person;
cout << "Book successfully issued to " << person << endl;
}
}

void returnBook() {
if (isIssued) {
isIssued = false;
issuedTo = "N/A";
cout << "Book successfully returned" << endl;
} else {
cout << "The book is not issued currently" << endl;
}
}

int getBookID() {
return bookID;
}
};

void addBook(Book books[], int &count, int id, string title, string author) {
books[count].setBookDetails(id, title, author);
count++;
}

int findBookIndex(Book books[], int count, int id) {


for (int i = 0; i < count; ++i) {
if (books[i].getBookID() == id)
return i;
}
return -1;
}

int main() {
const int MAX_BOOKS = 100;
Book books[MAX_BOOKS];
int bookCount = 0;
int choice;

do {
cout << "\nLibrary Management System Menu:\n";
cout << "1. Add a new book\n";
cout << "2. Issue a book\n";
cout << "3. Return a book\n";
cout << "4. Display all book details\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
int id;
string title, author;
cout << "Enter Book ID: ";
cin >> id;
cin.ignore();
cout << "Enter Title: ";
getline(cin, title);
cout << "Enter Author: ";
getline(cin, author);
addBook(books, bookCount, id, title, author);
cout << "Book added successfully!" << endl;
break;
}
case 2: {
int id;
cout << "Enter Book ID to issue: ";
cin >> id;
int index = findBookIndex(books, bookCount, id);
if (index != -1) {
string person;
cout << "Enter Person's Name: ";
cin >> person;
books[index].issueBook(person);
} else {
cout << "Book ID not found!" << endl;
}
break;
}
case 3: {
int id;
cout << "Enter Book ID to return: ";
cin >> id;
int index = findBookIndex(books, bookCount, id);
if (index != -1) {
books[index].returnBook();
} else {
cout << "Book ID not found!" << endl;
}
break;
}
case 4: {
for (int i = 0; i < bookCount; ++i) {
cout << "\nBook " << i + 1 << " details:\n";
books[i].displayDetails();
}
break;
}
case 5:
cout << "Exiting program...\n";
break;
default:
cout << "Invalid choice. Please enter a valid option.\n";
}
} while (choice != 5);

return 0;
}

OUTPUT :
===== Library Management System =====
1. Add a new book
2. Issue a book
3. Return a book
4. Display all books
5. Exit
Enter your choice: 1
Enter Book ID: 101
Enter Title: The Alchemist
Enter Author Name: Paulo Coelho
Book added successfully!

===== Library Management System =====


1. Add a new book
2. Issue a book
3. Return a book
4. Display all books
5. Exit
Enter your choice: 1
Enter Book ID: 102
Enter Title: Atomic Habits
Enter Author Name: James Clear
Book added successfully!

===== Library Management System =====


1. Add a new book
2. Issue a book
3. Return a book
4. Display all books
5. Exit
Enter your choice: 2
Enter Book ID to issue: 101
Enter Person's Name: Alice
Book successfully issued to Alice

===== Library Management System =====


1. Add a new book
2. Issue a book
3. Return a book
4. Display all books
5. Exit
Enter your choice: 2
Enter Book ID to issue: 101
Enter Person's Name: Bob
Sorry, the book is already issued to Alice

Enter your choice: 5


Exiting Library Management System. Goodbye!
Q3) Design a Student class that stores information about students, including their name, roll number, and marks.
Implement the following:

1. Static Data Members & Functions:


a) Keep a static variable to count the number of student objects created.
b) Use a static function to display the total number of students.
2. Array of Objects:
a) Store details of multiple students using an array.
3. Object Passing as Function Parameter:
a) Implement a function to compare two student objects and determine the student with higher marks.

Member variables:
string name;
string roll; float marks;
static int studentCount;

Member functions:
Void setStudentDetails(string name, string rollno, float marks); // initialize student details
Void display(); // Function to display student details void display()
static void showStudentCount() // Static function to display total number of students
void compare(Student s); // Function to compare two students' marks

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

class Student {
private:
string name;
string roll;
float marks;
static int studentCount;

public:
Student() {
studentCount++;
}

void setStudentDetails(string n, string r, float m) {


name = n;
roll = r;
marks = m;
}

void display() {
cout << "Name: " << name << endl;
cout << "Roll Number: " << roll << endl;
cout << "Marks: " << marks << endl;
}

static void showStudentCount() {


cout << "Total number of students: " << studentCount << endl;
}

void compare(Student s) {
if (marks > s.marks) {
cout << name << " has higher marks (" << marks << ") than " << s.name
<< " (" << s.marks << ")" << endl;
} else if (marks < s.marks) {
cout << s.name << " has higher marks (" << s.marks << ") than " <<
name << " (" << marks << ")" << endl;
} else {
cout << name << " and " << s.name << " have equal marks: " << marks <<
endl;
}
}
};

int Student::studentCount = 0;

int main() {
int n;
cout << "Enter number of students: ";
cin >> n;
cin.ignore();

Student students[100];

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


string name, roll;
float marks;
cout << "\nEnter details for Student " << i + 1 << ":\n";
cout << "Name: ";
getline(cin, name);
cout << "Roll Number: ";
getline(cin, roll);
cout << "Marks: ";
cin >> marks;
cin.ignore();
students[i].setStudentDetails(name, roll, marks);
}

cout << "\n--- Student Details ---\n";


for (int i = 0; i < n; ++i) {
cout << "\nStudent " << i + 1 << ":\n";
students[i].display();
}

Student::showStudentCount();

if (n >= 2) {
cout << "\n--- Comparing first two students ---\n";
students[0].compare(students[1]);
}

return 0;
}

OUTPUT :
Enter number of students: 2

Enter details for Student 1:


Name: RAM
Roll Number: 50
Marks: 99

Enter details for Student 2:


Name: RAJU
Roll Number: 39
Marks: 80

--- Student Details ---

Student 1:
Name: RAM
Roll Number: 50
Marks: 99

Student 2:
Name: RAJU
Roll Number: 39
Marks: 80

--- Comparing first two students ---


RAM has higher marks (99) than RAJU (80)

Q4) Student Grade Management System using C++. Implement a constructor to initialize the student's
roll number, name, and marks. Calculate total and average marks in the constructor. Implement a
destructor that displays a message when a student object is deleted.

Member variables:
int rollNumber;
string Name;
int marks[3]; (array of integers for 3 subjects of a particular student)
int totalMarks; (Calculate total marks of a particular student)
float averageMarks; (Average marks of a student / average of 3 subjects)
static int CountGrade[4]; // Count number of students for Each Grade (CountGrade[0] will contains count
of students who gets grade A, CountGrade[1] for grade B, CountGrade[2] for Grade C, CountGrade[3] for
grade F)

Member functions:
Student(5 parameters) // To initialize students details
char getGrade() // To determine grade of students based on their averageMarks
Assigning grades based on averageMarks:
100 → Grade A
75 - 89 → Grade B
50 - 74 → Grade C
< 50 → Grade F
Display() // Display details of all students one by one
Static void getStudentCount() // Will print number of students for each grade

In Main Section:
Create array of objects to store details of multiple students
Call parameterized constructor for each array index
Student Array[100]; // use one default empty constructor in class
For(i=0 to N){
Student S(arguments) // temporary object for parameterized constructor
Array[i] = S;
}
CODE :
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
int rollNumber;
string Name;
int marks[3];
int totalMarks;
float averageMarks;
static int CountGrade[4];
public:
Student() {
rollNumber = 0;
Name = "";
totalMarks = 0;
averageMarks = 0.0;
}

Student(int roll, string name, int m1, int m2, int m3) {
rollNumber = roll;
Name = name;
marks[0] = m1;
marks[1] = m2;
marks[2] = m3;

totalMarks = m1 + m2 + m3;
averageMarks = totalMarks / 3.0;

char grade = getGrade();


if (grade == 'A') CountGrade[0]++;
else if (grade == 'B') CountGrade[1]++;
else if (grade == 'C') CountGrade[2]++;
else CountGrade[3]++;
}

~Student() {
cout << "Student with Roll No. " << rollNumber << " is deleted." << endl;
}

char getGrade() {
if (averageMarks == 100)
return 'A';
else if (averageMarks >= 75 && averageMarks <= 89)
return 'B';
else if (averageMarks >= 50 && averageMarks < 75)
return 'C';
else
return 'F';
}

void display() {
cout << "\nRoll Number: " << rollNumber << endl;
cout << "Name: " << Name << endl;
cout << "Marks: " << marks[0] << ", " << marks[1] << ", " << marks[2] <<
endl;
cout << "Total Marks: " << totalMarks << endl;
cout << "Average Marks: " << averageMarks << endl;
cout << "Grade: " << getGrade() << endl;
}

static void getStudentCount() {


cout << "\nGrade Statistics:" << endl;
cout << "Grade A: " << CountGrade[0] << endl;
cout << "Grade B: " << CountGrade[1] << endl;
cout << "Grade C: " << CountGrade[2] << endl;
cout << "Grade F: " << CountGrade[3] << endl;
}
};

int Student::CountGrade[4] = {0, 0, 0, 0};

int main() {
int n;
cout << "Enter number of students: ";
cin >> n;
cin.ignore();

Student Array[100];

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


int roll, m1, m2, m3;
string name;

cout << "\nEnter details for Student " << i + 1 << ":\n";
cout << "Roll Number: ";
cin >> roll;
cin.ignore();
cout << "Name: ";
getline(cin, name);
cout << "Enter marks in 3 subjects: ";
cin >> m1 >> m2 >> m3;

Student S(roll, name, m1, m2, m3);


Array[i] = S;
}

cout << "\n--- Student Details ---";


for (int i = 0; i < n; ++i) {
Array[i].display();
}

Student::getStudentCount();
return 0;
}

OUTPUT :
Enter number of students: 2
Enter details for Student 1:
Roll Number: 1
Name: Alice
Enter marks in 3 subjects: 95 89 76

Enter details for Student 2:


Roll Number: 2
Name: Bob
Enter marks in 3 subjects: 30 45 55
--- Student Details ---

Roll Number: 1
Name: Alice
Marks: 95, 89, 76
Total Marks: 260
Average Marks: 86.6667
Grade: B

Roll Number: 2
Name: Bob
Marks: 30, 45, 55
Total Marks: 130
Average Marks: 43.3333
Grade: F

Grade Statistics:
Grade A: 0
Grade B: 1
Grade C: 0
Grade F: 1
Student with Roll No. 2 is deleted.
Student with Roll No. 1 is deleted.
Q5) Write a C++ program to initialize and display students’ data by using all three types of constructors.

Member variables:
string name;
int age;
float marks[3];

Member functions:
Default constructor // Make default value as follows (name:”unknown”, age = 0, marks = {0,0,0})
Parameterized constructor // Initialize variable with data
Copy constructor // Copy data of one to another object
Display() // Member function to display the details of students
Destructor // automatically called (print message about object destruction)

In Main Section:
Create array of objects to store details of multiple students (will call default constructor)
Display the data of all students
Call parameterized constructor with arguments
Display the data of all students
Copy objects of students to other objects
Display the data of all students

CODE :
#include <iostream>
#include <string>

using namespace std;


class Student {
private:
string name;
int age;
float marks[3];

public:
Student() {
name = "unknown";
age = 0;
for (int i = 0; i < 3; i++)
marks[i] = 0.0;
}
Student(string n, int a, float m1, float m2, float m3) {
name = n;
age = a;
marks[0] = m1;
marks[1] = m2;
marks[2] = m3;
}

Student(const Student &s) {


name = s.name;
age = s.age;
for (int i = 0; i < 3; i++)
marks[i] = s.marks[i];
}

void display() {
cout << "\nName: " << name;
cout << "\nAge: " << age;
cout << "\nMarks: ";
for (int i = 0; i < 3; i++)
cout << marks[i] << " ";
cout << endl;
}

~Student() {
cout << "Destructor called for student: " << name << endl;
}
};

int main() {
const int SIZE = 2;

cout << "\n--- Creating students using default constructor ---\n";


Student defaultStudents[SIZE];
for (int i = 0; i < SIZE; i++) {
cout << "\nStudent " << i + 1 << " details:";
defaultStudents[i].display();
}

cout << "\n--- Creating students using parameterized constructor ---\n";


Student s1("Alice", 20, 80.5, 90.0, 85.5);
Student s2("Bob", 19, 70.0, 75.0, 72.5);

s1.display();
s2.display();

cout << "\n--- Creating students using copy constructor ---\n";


Student copy1 = s1;
Student copy2 = s2;

copy1.display();
copy2.display();
cout << "\n--- Program End ---\n";
return 0;
}
OUTPUT :
--- Creating students using default constructor ---
Student 1 details:
Name: unknown
Age: 0
Marks: 0 0 0
Student 2 details:
Name: unknown
Age: 0
Marks: 0 0 0

--- Creating students using parameterized constructor ---


Name: Alice
Age: 20
Marks: 80.5 90 85.5
Name: Bob
Age: 19
Marks: 70 75 72.5

--- Creating students using copy constructor ---


Name: Alice
Age: 20
Marks: 80.5 90 85.5

Name: Bob
Age: 19
Marks: 70 75 72.5

--- Program End ---


Destructor called for student: Bob
Destructor called for student: Alice
Destructor called for student: Bob
Destructor called for student: Alice
Destructor called for student: unknown
Destructor called for student: unknown
Q6) Write a C++ program to perform basic arithmetic operations (addition, subtraction, and
multiplication) on complex numbers using a class. Implement the following requirements:

Define a class complex that has two private data members: real and imag for storing the real and
imaginary parts of a complex number.

Include:
A constructor to initialize the complex number (with default values of 0 for both parts).
A member function input() to take input from the user for the real and imaginary parts.
A member function display() to print the complex number in the standard form (a + bi or a - bi).

Use friend functions to perform:


Addition of two complex numbers
Subtraction of two complex numbers
Multiplication of two complex numbers

In the main() function:


Prompt the user to input two complex numbers.
Display both complex numbers.
Display the result of their addition, subtraction, and multiplication using the respective friend functions.

CODE :
#include <iostream>
using namespace std;

class complex {
private:
int real;
int imag;

public:
complex(int r = 0, int i = 0) {
real = r;
imag = i;
}

void input() {
cout << "Enter real and imaginary parts: ";
cin >> real >> imag;
}
void display() const {
cout << real;
if (imag >= 0) {
cout << " + " << imag << "i" << endl;
} else {
cout << " - " << -imag << "i" << endl;
}
}

friend complex add(const complex &c1, const complex &c2);


friend complex subtract(const complex &c1, const complex &c2);
friend complex multiply(const complex &c1, const complex &c2);
};

complex add(const complex &c1, const complex &c2) {


return complex(c1.real + c2.real, c1.imag + c2.imag);
}

complex subtract(const complex &c1, const complex &c2) {


return complex(c1.real - c2.real, c1.imag - c2.imag);
}

complex multiply(const complex &c1, const complex &c2) {


return complex((c1.real * c2.real - c1.imag * c2.imag),
(c1.real * c2.imag + c1.imag * c2.real));
}

int main() {
complex c1, c2;
cout << "Enter the 1st complex number:\n";
c1.input();
cout << "Enter the 2nd complex number:\n";
c2.input();

cout << "\n1st complex number: ";


c1.display();
cout << "2nd complex number: ";
c2.display();

complex sum = add(c1, c2);


cout << "\nAddition: ";
sum.display();

complex sub = subtract(c1, c2);


cout << "\nSubtraction: ";
sub.display();

complex pro = multiply(c1, c2);


cout << "\nMultiplication: ";
pro.display();

return 0;
}
OUTPUT :
Enter the 1st complex number:
Enter real and imaginary parts: 2 9
Enter the 2nd complex number:
Enter real and imaginary parts: 6 1

1st complex number: 2 + 9i


2nd complex number: 6 + 1i

Addition: 8 + 10i

Subtraction: -4 + 8i

Multiplication: 3 + 56i
Q7) Design a C++ program for a library management system to manage book borrowings.

Person – Base class with:


name (string)
userID (int)
display() – to display user details.

Student – Derived class with:


bookBorrowed (string) – stores the name of the borrowed book
daysBorrowed (int) – number of days the book is borrowed

Fine Calculation:
No fine for the first 7 days.
₹2 per day after 7 days.

Task:
 Take input for the student's details and borrowed book information.
 Display user details, borrowed book name, and fine (if applicable).

In Main Function:
1) Create one object of Base Class (Call parameterized constructor)
2) Call display function and calculate fine inside display()
3) Call returnBook();
4) Call display();

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

class Person {
protected:
string name;
int userID;

public:
Person(string n, int id) {
name = n;
userID = id;
}

virtual void display() {


cout << "Name: " << name << endl;
cout << "User ID: " << userID << endl;
}
};

class Student : public Person {


private:
string bookBorrowed;
int daysBorrowed;

public:
Student(string n, int id, string book, int days)
: Person(n, id) {
bookBorrowed = book;
daysBorrowed = days;
}

void display() override {


Person::display();
cout << "Book Borrowed: " << bookBorrowed << endl;
cout << "Days Borrowed: " << daysBorrowed << endl;

int fine = 0;
if (daysBorrowed > 7) {
fine = (daysBorrowed - 7) * 2;
}
cout << "Fine: ₹" << fine << endl;
}

void returnBook() {
cout << "\nReturning book: " << bookBorrowed << endl;
bookBorrowed = "";
daysBorrowed = 0;
}
};

int main() {
string name, book;
int userID, days;

cout << "Enter student name: ";


getline(cin, name);
cout << "Enter user ID: ";
cin >> userID;
cin.ignore();

cout << "Enter book name: ";


getline(cin, book);
cout << "Enter number of days the book is borrowed: ";
cin >> days;

Student s(name, userID, book, days);

cout << "\n--- User & Book Details ---\n";


s.display();

s.returnBook();

cout << "\n--- Updated Details After Return ---\n";


s.display();

return 0;
}

OUTPUT :
Enter student name: Aryan Mehta
Enter user ID: 202
Enter book name: Data Structures in C++
Enter number of days the book is borrowed: 12

--- User & Book Details ---


Name: Aryan Mehta
User ID: 202
Book Borrowed: Data Structures in C++
Days Borrowed: 12
Fine: ₹10

Returning book: Data Structures in C++

--- Updated Details After Return ---


Name: Aryan Mehta
User ID: 202
Book Borrowed:
Days Borrowed: 0
Fine: ₹0
Q8) Write a C++ program to perform various operations on Complex Number objects by overloading the
following operators: +, -, *, %, /

In Main Function:
1) Create two objects of Complex class and initialize data using parameterized constructor
2) Perform the mentioned operations

CODE :
#include <iostream>
#include <cmath>
using namespace std;

class Complex {
private:
int real;
int imag;

public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}

void display() const {


cout << real;
if (imag >= 0)
cout << " + " << imag << "i" << endl;
else
cout << " - " << -imag << "i" << endl;
}

Complex operator+(const Complex &c) const {


return Complex(real + c.real, imag + c.imag);
}

Complex operator-(const Complex &c) const {


return Complex(real - c.real, imag - c.imag);
}

Complex operator*(const Complex &c) const {


return Complex(real * c.real - imag * c.imag,
real * c.imag + imag * c.real);
}

Complex operator/(const Complex &c) const {


int denom = c.real * c.real + c.imag * c.imag;
int r = (real * c.real + imag * c.imag) / denom;
int i = (imag * c.real - real * c.imag) / denom;
return Complex(r, i);
}

Complex operator%(const Complex &c) const {


return Complex(real % c.real, imag % c.imag);
}
};

int main() {
Complex c1(7, 5);
Complex c2(2, 3);

cout << "First Complex Number: ";


c1.display();

cout << "Second Complex Number: ";


c2.display();

Complex sum = c1 + c2;


cout << "\nAddition: ";
sum.display();

Complex diff = c1 - c2;


cout << "Subtraction: ";
diff.display();

Complex prod = c1 * c2;


cout << "Multiplication: ";
prod.display();

Complex div = c1 / c2;


cout << "Division: ";
div.display();

Complex mod = c1 % c2;


cout << "Modulus (Real % Real, Imag % Imag): ";
mod.display();

return 0;
}

OUTPUT :
First Complex Number: 7 + 5i
Second Complex Number: 2 + 3i

Addition: 9 + 8i
Subtraction: 5 + 2i
Multiplication: 1 + 31i
Division: 2 + -1i
Modulus (Real % Real, Imag % Imag): 1 + 2i
Q9) Area-Based Shape Sorting and Visualization

Objective:
Use runtime polymorphism to design a system that:
 Stores various types of shapes (Circle, Rectangle, Triangle, etc.).
 Calculates area and perimeter dynamically using virtual functions.
 Sorts shapes by area.

Problem Statement:
Design a base class Shape with the following:
 Pure virtual functions:
o double area()
o double perimeter()
o void display()

Derive the following classes:


 Circle – takes radius
 Rectangle – takes length and width
 Triangle – takes sides a, b, and c

Create a vector of Shape* and do the following:


1. Take user input to create different shapes.
2. Display all shapes with area and perimeter.
3. Sort shapes in descending order of area.

CODE :
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;

class Shape {
public:
virtual double area() const = 0;
virtual double perimeter() const = 0;
virtual void display() const = 0;
virtual ~Shape() {}
};

class Circle : public Shape {


double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
double perimeter() const override {
return 2 * M_PI * radius;
}
void display() const override {
cout << "Circle - Radius: " << radius
<< ", Area: " << area()
<< ", Perimeter: " << perimeter() << endl;
}
};

class Rectangle : public Shape {


double length, width;
public:
Rectangle(double l, double w) : length(l), width(w) {}
double area() const override {
return length * width;
}
double perimeter() const override {
return 2 * (length + width);
}
void display() const override {
cout << "Rectangle - Length: " << length << ", Width: " << width
<< ", Area: " << area()
<< ", Perimeter: " << perimeter() << endl;
}
};

class Triangle : public Shape {


double a, b, c;
public:
Triangle(double x, double y, double z) : a(x), b(y), c(z) {}
double area() const override {
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
double perimeter() const override {
return a + b + c;
}
void display() const override {
cout << "Triangle - Sides: " << a << ", " << b << ", " << c
<< ", Area: " << area()
<< ", Perimeter: " << perimeter() << endl;
}
};
bool compareByAreaDesc(Shape* s1, Shape* s2) {
return s1->area() > s2->area();
}

int main() {
vector<Shape*> shapes;
int choice;

do {
cout << "\nMenu:\n1. Add Circle\n2. Add Rectangle\n3. Add Triangle\n4.
Display All\n5. Sort by Area\n0. Exit\nChoice: ";
cin >> choice;

if (choice == 1) {
double r;
cout << "Enter radius: ";
cin >> r;
shapes.push_back(new Circle(r));
} else if (choice == 2) {
double l, w;
cout << "Enter length and width: ";
cin >> l >> w;
shapes.push_back(new Rectangle(l, w));
} else if (choice == 3) {
double a, b, c;
cout << "Enter sides a, b, c: ";
cin >> a >> b >> c;
if (a + b > c && a + c > b && b + c > a) {
shapes.push_back(new Triangle(a, b, c));
} else {
cout << "Invalid triangle sides!" << endl;
}
} else if (choice == 4) {
cout << "\nDisplaying all shapes:\n";
for (const auto& shape : shapes) {
shape->display();
}
} else if (choice == 5) {
sort(shapes.begin(), shapes.end(), compareByAreaDesc);
cout << "\nShapes sorted by descending area:\n";
for (const auto& shape : shapes) {
shape->display();
}
}

} while (choice != 0);

for (auto shape : shapes) {


delete shape;
}

return 0;
}
OUTPUT :
Menu:
1. Add Circle
2. Add Rectangle
3. Add Triangle
4. Display All
5. Sort by Area
0. Exit
Choice: 1
Enter radius: 4

Menu:
1. Add Circle
2. Add Rectangle
3. Add Triangle
4. Display All
5. Sort by Area
0. Exit
Choice: 2
Enter length and width: 4 8

Menu:
1. Add Circle
2. Add Rectangle
3. Add Triangle
4. Display All
5. Sort by Area
0. Exit
Choice: 3
Enter sides a, b, c: 3 4 5

Menu:
1. Add Circle
2. Add Rectangle
3. Add Triangle
4. Display All
5. Sort by Area
0. Exit
Choice: 4

Displaying all shapes:


Circle - Radius: 4, Area: 50.2655, Perimeter: 25.1327
Rectangle - Length: 4, Width: 8, Area: 32, Perimeter: 24
Triangle - Sides: 3, 4, 5, Area: 6, Perimeter: 12

Menu:
1. Add Circle
2. Add Rectangle
3. Add Triangle
4. Display All
5. Sort by Area
0. Exit
Choice: 5

Shapes sorted by descending area:


Circle - Radius: 4, Area: 50.2655, Perimeter: 25.1327
Rectangle - Length: 4, Width: 8, Area: 32, Perimeter: 24
Triangle - Sides: 3, 4, 5, Area: 6, Perimeter: 12

Menu:
1. Add Circle
2. Add Rectangle
3. Add Triangle
4. Display All
5. Sort by Area
0. Exit
Choice: 0

You might also like