0% found this document useful (0 votes)
46 views51 pages

All Assi.......

The document contains multiple C++ programming assignments that cover various concepts such as structures, classes, encapsulation, and recursion. It includes programs for managing student data, employee details, calculating simple interest, and computing time differences, as well as calculating triangular numbers recursively. Each assignment provides specific requirements and example implementations for the tasks.

Uploaded by

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

All Assi.......

The document contains multiple C++ programming assignments that cover various concepts such as structures, classes, encapsulation, and recursion. It includes programs for managing student data, employee details, calculating simple interest, and computing time differences, as well as calculating triangular numbers recursively. Each assignment provides specific requirements and example implementations for the tasks.

Uploaded by

niyazansari677
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 51

////Assignment 1

///*Q1. Write a program in c to define a structure student with members


roll_number(int) , name(char/array) and cgpa (float).
//a) Define a function "getdata" to input Roll_number,Name and Cgpa from user.
//b)Define another function "printdata" to print line data on output console.*/

//#include <stdio.h>
//#include <string> // Note: This is included, but not used in this example
//
//struct Student {
// int roll_number;
// char name[20];
// float cgpa;
//};
//
//// Function to get data for a Student object
//void getdata(Student &s) { // Use reference instead of pointer
// printf("Enter Name: ");
// scanf("%19s", s.name); // Limit input to avoid overflow
//
// printf("Enter Roll Number: ");
// scanf("%d", &s.roll_number);
//
// printf("Enter CGPA: ");
// scanf("%f", &s.cgpa);
//}
//
//// Function to print data for a Student object
//void printdata(const Student &s) { // Use const reference for efficiency
// printf("Name: %s\n", s.name);
// printf("Roll Number: %d\n", s.roll_number);
// printf("CGPA: %.2f\n", s.cgpa);
//}
//
//int main() {
// Student student; // Define a Student object
//
// getdata(student); // Pass by reference
// printdata(student); // Pass by const reference
//
// return 0;
//}
//Q2. Modify the above code to accept the print and data of 10 student using array
of structure

#include <stdio.h>

struct Student {
int roll_number;
char name[20];
float cgpa;
};

// Function to get data for a Student object


void getdata(Student &s) {
printf("Enter Name: ");
scanf("%19s", s.name); // Limit input to avoid overflow
printf("Enter Roll Number: ");
scanf("%d", &s.roll_number);

printf("Enter CGPA: ");


scanf("%f", &s.cgpa);
}

// Function to print data for a Student object


void printdata(const Student &s) {
printf("Name: %s\n", s.name);
printf("Roll Number: %d\n", s.roll_number);
printf("CGPA: %.2f\n", s.cgpa);
}

int main() {
Student students[10]; // Define an array of Student objects
int i;

// Input data for each student


for (i = 0; i < 10; ++i) {
printf("\nEnter details for student %d:\n", i + 1);
getdata(students[i]); // Pass by reference
}

// Print data for each student


printf("\nStudent Details:\n");
for (i = 0; i < 10; ++i) {
printf("\nDetails for student %d:\n", i + 1);
printdata(students[i]); // Pass by const reference
}

return 0;
}

//ASSIGNMENT 2

/*Q1. define a structure student with members roll_number(int) , name(char/array)


and cgpa (float).
a) Define a function "Setdata" to input Roll_number,Name and Cgpa from user and set
it to any variable of structure defined in the main .
b)Define a function "showdata" to printdata of any variable of the structure
defined in main .
write a program in C++ to define three separate variable of the above structure in
the main and implement the above 2 functions .
*/

#include <iostream>
#include <string>

using namespace std;

// Define a structure named 'Student' that holds information about a student


struct Student {
int roll_number; // Integer to store the roll number of the student
string name; // String to store the name of the student
float cgpa; // Float to store the CGPA of the student
};

// Function to input data into a Student object (passed by reference)


void Setdata(Student &s) {
// Prompt the user to enter the roll number and store it in the roll_number
variable
cout << "Enter Roll Number: ";
cin >> s.roll_number;

// Prompt the user to enter the name and store it in the name variable
cout << "Enter Name: ";
cin >> s.name;

// Prompt the user to enter the CGPA and store it in the cgpa variable
cout << "Enter CGPA: ";
cin >> s.cgpa;
}

// Function to display the data of a Student object (passed as a constant


reference)
void showdata(const Student &s) {
// Print the roll number, name, and CGPA of the student
cout << "Roll Number: " << s.roll_number << endl;
cout << "Name: " << s.name << endl;
cout << "CGPA: " << s.cgpa << endl;
}

int main() {
// Declare three Student variables (s1, s2, and s3) to store the details of
three different students
Student s1, s2, s3;

// Call the Setdata function to input data for each student


Setdata(s1);
Setdata(s2);
Setdata(s3);

// Call the showdata function to display the data of each student


showdata(s1);
showdata(s2);
showdata(s3);

return 0; // Indicate successful program termination


}

//ASSIGNMENT 3

/* Q1- write a program in C++ to create a class employee, take three data memebers
Name,Employee_id,Salary.
Input the data and display the detail using two separate functions .
Use the concept of encapsulation .Also in the same program display the size of
objects that are created. */

#include <iostream>
#include <string>

using namespace std;

// Definition of the Employee class


class Employee {
private:
// Private member variables of the Employee class
string name; // To store the employee's name
int employee_id; // To store the employee's ID
float salary; // To store the employee's salary

public:
// Function to input employee details from the user
void inputData() {
// Asking for the employee's name
cout << "Enter Name: ";

// Clearing the input buffer to prevent any issues with reading the name
cin.ignore();

// Using getline to allow for multi-word names


getline(cin, name);

// Asking for the employee's ID


cout << "Enter Employee ID: ";
cin >> employee_id;

// Asking for the employee's salary


cout << "Enter Salary: ";
cin >> salary;
}

// Function to display employee details


void displayData() const {
// Printing the employee's name
cout << "Name: " << name << endl;

// Printing the employee's ID


cout << "Employee ID: " << employee_id << endl;

// Printing the employee's salary


cout << "Salary: " << salary << endl;
}

// Static function to display the size of an Employee object


// Static means this function belongs to the class itself and not a specific
object
static void displayObjectSize() {
// Printing the size of an Employee object in bytes
cout << "Size of Employee object: " << sizeof(Employee) << " bytes" <<
endl;
}
};

// Main function that runs the program


int main() {
// Creating two Employee objects, emp1 and emp2
Employee emp1, emp2;

// Input and display details for Employee 1


cout << "Enter details for Employee 1:\n";
emp1.inputData(); // Call to inputData() to get details for Employee 1

// Input and display details for Employee 2


cout << "\nEnter details for Employee 2:\n";
emp2.inputData(); // Call to inputData() to get details for Employee 2

// Display the details of Employee 1


cout << "\nEmployee 1 details:\n";
emp1.displayData(); // Call to displayData() to print Employee 1 details

// Display the details of Employee 2


cout << "\nEmployee 2 details:\n";
emp2.displayData(); // Call to displayData() to print Employee 2 details

// Call the static function to display the size of an Employee object


Employee::displayObjectSize();

return 0; // Return 0 to indicate successful execution


}

/* Q2- Write a program in c++ to calculate the simple intrest.Hide the data and the
function used to calculate the intrest .
Invoke the private function using a public function to get the result .*/

#include <iostream>

using namespace std;

// Define a class 'InterestCalculator' to calculate simple interest


class InterestCalculator {
private:
// Private member variables to store the principal, rate, time, and calculated
interest
double principal, rate, time, interest;

// Private function to calculate the interest using the simple interest formula
void calculateInterest() {
interest = (principal * rate * time) / 100;
}

public:
// Public function to set the values for principal, rate, and time
// It also calls the calculateInterest function to compute the interest
void setValues(double p, double r, double t) {
principal = p; // Set the principal amount
rate = r; // Set the interest rate
time = t; // Set the time period
calculateInterest(); // Calculate the interest based on the input values
}
// Public function to return the calculated interest
double getInterest() {
return interest; // Return the value of the interest that was calculated
}
};

int main() {
// Create an object of the 'InterestCalculator' class
InterestCalculator calculator;

// Variables to store user inputs for principal, rate, and time


double principal, rate, time;

// Prompt the user to input the principal amount


cout << "Enter principal amount: ";
cin >> principal; // Get the input and store it in the 'principal' variable

// Prompt the user to input the interest rate


cout << "Enter interest rate: ";
cin >> rate; // Get the input and store it in the 'rate' variable

// Prompt the user to input the time period


cout << "Enter time period: ";
cin >> time; // Get the input and store it in the 'time' variable

// Call the setValues function of the 'calculator' object to set the inputs
// and calculate the interest based on the inputs
calculator.setValues(principal, rate, time);

// Retrieve the calculated interest using the getInterest function


double calculatedInterest = calculator.getInterest();

// Output the calculated simple interest to the console


cout << "Simple interest: " << calculatedInterest << endl;

return 0; // End the program


}

/* Q3- Write a program to create a class time, accept hour,min,sec through data
members.
Accept two diffrent instances of time and calculate the diffrence of time .*/
#include <iostream>
#include <iomanip> // For setting output format
using namespace std;
// Define a class to represent Time
class Time {
public:
// Public member variables for hour, minute, and second
int hour;
int minute;
int second;

// Member function to input time from the user


void inputTime() {
cout << "Enter hour (0-23): ";
cin >> hour; // Read the hour from the user (between 0 and 23)
cout << "Enter minute (0-59): ";
cin >> minute; // Read the minute from the user (between 0 and 59)
cout << "Enter second (0-59): ";
cin >> second; // Read the second from the user (between 0 and 59)
}

// Member function to display time in HH:MM:SS format


void displayTime() const {
// setw(2) ensures that the width is 2 digits, setfill('0') fills leading
zero if necessary
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << endl;
}
};

// Function to check if a given Time object represents a valid time


bool isTimeValid(const Time& t) {
// Check if hour is between 0 and 23, minute and second are between 0 and 59
return (t.hour >= 0 && t.hour <= 23) &&
(t.minute >= 0 && t.minute <= 59) &&
(t.second >= 0 && t.second <= 59);
}

// Function to calculate and display the difference between two Time objects
void calculateDifference(const Time& t1, const Time& t2) {
// Validate both time objects to ensure they contain valid time values
if (!isTimeValid(t1) || !isTimeValid(t2)) {
cout << "Invalid time input. Please try again." << endl;
return; // Exit the function if time is invalid
}

// Ensure that the second time is not larger than the first time
if (t1.hour < t2.hour ||
(t1.hour == t2.hour && t1.minute < t2.minute) ||
(t1.hour == t2.hour && t1.minute == t2.minute && t1.second < t2.second)) {
cout << "Error: The second time cannot be later than the first time." <<
endl;
return; // Exit the function if the second time is later
}

// Convert both time objects to total seconds since 00:00:00


int totalSeconds1 = t1.hour * 3600 + t1.minute * 60 + t1.second;
int totalSeconds2 = t2.hour * 3600 + t2.minute * 60 + t2.second;

// Calculate the difference in seconds between the two times


int differenceInSeconds = totalSeconds1 - totalSeconds2;

// Convert the difference back into hours, minutes, and seconds


int hours = differenceInSeconds / 3600; // Calculate hours
differenceInSeconds %= 3600; // Get the remaining seconds after extracting
hours
int minutes = differenceInSeconds / 60; // Calculate minutes
int seconds = differenceInSeconds % 60; // Remaining seconds after extracting
minutes

// Display the time difference in HH:MM:SS format


cout << "Time difference: "
<< setw(2) << setfill('0') << hours << ":"
<< setw(2) << setfill('0') << minutes << ":"
<< setw(2) << setfill('0') << seconds << endl;
}

int main() {
Time time1, time2; // Create two Time objects to store user input
char choice; // Variable to store the user's choice for continuing or exiting

do {
// Prompt the user to enter the first time
cout << "Enter first time:" << endl;
time1.inputTime(); // Call inputTime() to get user input for time1

// Prompt the user to enter the second time


cout << "Enter second time:" << endl;
time2.inputTime(); // Call inputTime() to get user input for time2

// Call calculateDifference to compute and display the time difference


calculateDifference(time1, time2);

// Ask the user if they want to calculate another time difference


cout << "Do you want to calculate another time difference? (y/n): ";
cin >> choice; // Read the user's choice ('y' or 'n')
} while (choice == 'y' || choice == 'Y'); // Continue if the user enters 'y'
or 'Y'

return 0; // Exit the program


}

//ASSIGNMENT 4

/* Q1-write a c++ program in C++ to calculate triangular number by creating a


member function .
Call it recursively.*/

#include <iostream> // Include input-output stream library to use cin and cout

using namespace std; // Use the standard namespace to avoid prefixing std:: before
standard functions

// Define a class called TriangularNumber


class TriangularNumber {
public:
// This is a recursive function to calculate the nth triangular number
int calculateTriangularNumber(int n) {
// Base case: If n is 0, the triangular number is 0
if (n == 0) {
return 0;
}
// Recursive case: Add n to the triangular number of (n - 1)
else {
return n + calculateTriangularNumber(n - 1);
}
}
};

int main() {
TriangularNumber tn; // Create an object of the TriangularNumber class
int num; // Declare a variable to store user input

// Prompt the user to enter a positive integer


cout << "Enter a positive integer: ";
cin >> num; // Get the input from the user and store it in 'num'

// Call the calculateTriangularNumber function using the 'tn' object


// and store the result in 'result'
int result = tn.calculateTriangularNumber(num);

// Display the result to the user


cout << "The triangular number of " << num << " is: " << result << endl;

return 0; // Return 0 to indicate successful execution


}

/* Q2- Write a program in c++ to create a class student , take data members as
student name,ge,roll_no,branch and display the data through member functions.
Make university code a static member variable and acess it through static
functions.*/

#include <iostream> // This header file is included to use input-output streams


(cin, cout)
#include <string> // This header file is included to use the string class

using namespace std; // We are using the standard namespace to avoid prefixing
'std::' to standard library names

// Define a class named "Student" to represent student data


class Student {
private:
// Private member variables (only accessible within the class)
string name; // To store the name of the student
int age; // To store the age of the student
int rollNo; // To store the roll number of the student
string branch; // To store the branch of the student

public:
// Static member variable to store a university code that is shared among all
instances of the class
static string universityCode;

// Member function to accept input data from the user


void acceptData() {
// Input student name using getline to handle spaces in names
cout << "Enter student name: ";
getline(cin, name);

// Input student age


cout << "Enter student age: ";
cin >> age;

// Clear the input buffer before reading another string (getline)


cin.ignore();

// Input student roll number


cout << "Enter student roll number: ";
cin >> rollNo;

// Clear the input buffer again before reading another string (getline)
cin.ignore();

// Input student branch using getline to handle spaces in branch names


cout << "Enter student branch: ";
getline(cin, branch);
}

// Member function to display the data stored in the object


void displayData() {
cout << "\nStudent Name: " << name << endl;
cout << "Student Age: " << age << endl;
cout << "Student Roll No: " << rollNo << endl;
cout << "Student Branch: " << branch << endl;
cout << "University Code: " << getUniversityCode() << endl; // Access
static member function to get the university code
}

// Static member function to access the static variable "universityCode"


// This function can be called without an object of the class
static string getUniversityCode() {
return universityCode;
}

// Static member function to set the university code


static void setUniversityCode(string code) {
universityCode = code;
}
};

// Initialize the static member variable "universityCode" with the value "XYZ123"
string Student::universityCode = "XYZ123";

int main() {
// Create an object of the class "Student"
Student s1;

// Call the member function to accept data from the user


s1.acceptData();

// Call the member function to display the student's data


s1.displayData();

// Access the static member function using the class name to get the university
code
cout << "\nUniversity Code: " << Student::getUniversityCode() << endl;

return 0;
}

/
***********************************************************************************
**********************
***********************************************************************************
***********************/

/* Q3- Extend the question 2 to accept and print the details of 5 students*/

#include <iostream>
#include <string>

using namespace std;

// Class to store student data and handle operations


class Student {
private:
string name; // Private member to store the student's name
int age; // Private member to store the student's age
int rollNo; // Private member to store the student's roll number
string branch; // Private member to store the student's branch

public:
static string universityCode; // Static member variable to store university
code (common for all students)

// Member function to accept data from the user


void acceptData() {
cout << "Enter student name: ";
getline(cin, name); // Input the student's name
cout << "Enter student age: ";
cin >> age; // Input the student's age
cin.ignore(); // Clear the input buffer to avoid issues with getline
after cin
cout << "Enter student roll number: ";
cin >> rollNo; // Input the student's roll number
cin.ignore(); // Clear the input buffer again for the same reason
cout << "Enter student branch: ";
getline(cin, branch); // Input the student's branch
}

// Member function to display the student's data


void displayData() {
cout << "\nStudent Name: " << name << endl; // Display the
student's name
cout << "Student Age: " << age << endl; // Display the
student's age
cout << "Student Roll No: " << rollNo << endl; // Display the
student's roll number
cout << "Student Branch: " << branch << endl; // Display the
student's branch
cout << "University Code: " << getUniversityCode() << endl; // Display the
university code using a static function
}
// Static function to get the university code
static string getUniversityCode() {
return universityCode; // Return the static university code
}

// Static function to set the university code


static void setUniversityCode(string code) {
universityCode = code; // Set a new value for the static university code
}
};

// Initialize the static member variable for the university code


string Student::universityCode = "XYZ123"; // Default university code is set to
"XYZ123"

int main() {
const int numStudents = 5; // Define a constant for the number of students
Student students[numStudents]; // Create an array of 5 Student objects

// Loop to input data for each student


for (int i = 0; i < numStudents; ++i) {
cout << "\nEnter details for student " << i + 1 << ":" << endl; // Prompt
for each student
students[i].acceptData(); // Call the acceptData() function for each
student
}

// Display data for all students


cout << "\nStudent Details:\n";
for (int i = 0; i < numStudents; ++i) {
students[i].displayData(); // Call the displayData() function to print
student details
cout << endl; // Add a blank line after each student's details
}

// Display the university code (static variable shared among all students)
cout << "\nUniversity Code: " << Student::getUniversityCode() << endl;

return 0; // Exit the program


}

//ASSIGNMENT 5

/*Q1. Write a programn to calculate the sumunation of area of rectungle, triangle


and circle using friend function.
Use multiple classes and a friend fuction. You nced to create three classes:
Rectangle, Triangle, and Circle.
Each class will have privale data members to store necessary dimensions. Create
three friend functions, one for cach shape, to calculate the area.
A final class will use these friend functions to calculate the fotal area*/

#include <iostream>
using namespace std;

// Class to represent a Rectangle


class Rectangle {
private:
double length, breadth; // Private data members to store the dimensions of the
rectangle

public:
// Function to input the length and breadth of the rectangle
void input() {
cin >> length >> breadth; // Taking input from the user
}

// Function to display the length and breadth of the rectangle


void show() const {
cout << "Length: " << length << ", Breadth: " << breadth << endl;
}

// Friend function declaration to calculate the area of the rectangle


// This function is a friend because it needs access to private members (length
and breadth)
friend double calrec(const Rectangle &r);
};

// Definition of the friend function to calculate the area of the rectangle


double calrec(const Rectangle &r) {
return r.length * r.breadth; // Area formula: length * breadth
}

// Class to represent a Triangle


class Triangle {
private:
double height, base; // Private data members to store the dimensions of the
triangle

public:
// Function to input the height and base of the triangle
void input() {
cin >> height >> base; // Taking input from the user
}

// Function to display the height and base of the triangle


void show() const {
cout << "Height: " << height << ", Base: " << base << endl;
}

// Friend function declaration to calculate the area of the triangle


// This function is a friend because it needs access to private members (height
and base)
friend double caltri(const Triangle &t);
};
// Definition of the friend function to calculate the area of the triangle
double caltri(const Triangle &t) {
return 0.5 * t.height * t.base; // Area formula: 0.5 * base * height
}

// Class to represent a Circle


class Circle {
private:
double radius; // Private data member to store the radius of the circle

public:
// Function to input the radius of the circle
void input() {
cin >> radius; // Taking input from the user
}

// Function to display the radius of the circle


void show() const {
cout << "Radius: " << radius << endl;
}

// Friend function declaration to calculate the area of the circle


// This function is a friend because it needs access to the private member
(radius)
friend double calcir(const Circle &c);
};

// Definition of the friend function to calculate the area of the circle


double calcir(const Circle &c) {
return 3.14 * c.radius * c.radius; // Area formula: p * r^2
}

int main() {
// Working with the Rectangle
Rectangle r1;
cout << "Enter dimensions for Rectangle:" << endl;
r1.input(); // Input the length and breadth of the rectangle
r1.show(); // Display the dimensions of the rectangle
double ar = calrec(r1); // Calculate the area using the friend function
cout << "Area of Rectangle: " << ar << endl; // Display the area

// Working with the Triangle


Triangle t1;
cout << "Enter dimensions for Triangle:" << endl;
t1.input(); // Input the height and base of the triangle
t1.show(); // Display the dimensions of the triangle
double at = caltri(t1); // Calculate the area using the friend function
cout << "Area of Triangle: " << at << endl; // Display the area

// Working with the Circle


Circle c1;
cout << "Enter radius for Circle:" << endl;
c1.input(); // Input the radius of the circle
c1.show(); // Display the radius of the circle
double ac = calcir(c1); // Calculate the area using the friend function
cout << "Area of Circle: " << ac << endl; // Display the area

return 0;
}

/* Q2- write a friend function in c++ to add 2 objects of the same class
and display the sum of the two values which contains one integer value and one
floating point value.*/

#include <iostream> // Required for input/output operations (cin, cout)

using namespace std;

// Definition of the class "Number"


class Number {
public:
int integerValue; // This member variable will store an integer value
float floatingValue; // This member variable will store a floating-point value

// Constructor to initialize the class members


Number(int i, float f) : integerValue(i), floatingValue(f) {
// The constructor takes two arguments: an integer and a float.
// It initializes integerValue with i and floatingValue with f.
}

// Declaration of the friend function


// A friend function can access the private and protected members of the class
friend void add(Number& num1, Number& num2);
};

// Definition of the friend function


// This function will add the integer and floating-point values from two "Number"
objects
void add(Number& num1, Number& num2) {
// Sum the integer values of num1 and num2
int sumInt = num1.integerValue + num2.integerValue;

// Sum the floating-point values of num1 and num2


float sumFloat = num1.floatingValue + num2.floatingValue;

// Print the sum of the integer values


cout << "Sum of integer values: " << sumInt << endl;

// Print the sum of the floating-point values


cout << "Sum of floating values: " << sumFloat << endl;
}

int main() {
// Create two objects of the class "Number" with initial values
Number num1(5, 2.5); // num1 is created with integer 5 and float 2.5
Number num2(3, 1.7); // num2 is created with integer 3 and float 1.7

// Call the friend function "add" to add the values of num1 and num2
add(num1, num2);

return 0; // Return 0 to indicate the program finished successfully


}
/* Q3-Write a program in C++ to exchange the object values using friend function.
Create separate member functions to accept and display the values of the two member
variables.
The friend function should have the logic for exchanging both values of two
objects.*/

#include <iostream>

using namespace std;

// Class definition for MyClass


class MyClass {
private:
int value; // Private member variable that stores the value for each object

public:
// Member function to accept a value and store it in the 'value' variable
void acceptValue(int val) {
value = val; // Assign the passed value to the object's 'value' variable
}

// Member function to display the current value of the 'value' variable


void displayValue() {
cout << "Value: " << value << endl; // Print the value of the object to
the console
}

// Friend function declaration


// This friend function can access the private members of the class
// It is responsible for swapping the values between two objects
friend void exchangeValues(MyClass &obj1, MyClass &obj2);
};

// Friend function to exchange the values of two MyClass objects


void exchangeValues(MyClass &obj1, MyClass &obj2) {
// Temporarily store obj1's value in a temporary variable
int temp = obj1.value;

// Assign obj2's value to obj1's value


obj1.value = obj2.value;

// Assign the temporary value (which is obj1's original value) to obj2's value
obj2.value = temp;
}

// Main function where the program starts execution


int main() {
MyClass obj1, obj2; // Create two objects of MyClass

// Assign initial values to both objects using acceptValue() member function


obj1.acceptValue(10); // obj1's value is set to 10
obj2.acceptValue(20); // obj2's value is set to 20

// Display the values of both objects before the exchange


cout << "Before exchange:" << endl;
obj1.displayValue(); // Output: Value: 10
obj2.displayValue(); // Output: Value: 20

// Call the friend function to exchange the values between obj1 and obj2
exchangeValues(obj1, obj2);

// Display the values of both objects after the exchange


cout << "After exchange:" << endl;
obj1.displayValue(); // Output: Value: 20 (obj1 now has obj2's original value)
obj2.displayValue(); // Output: Value: 10 (obj2 now has obj1's original value)

return 0; // End of the program


}

/*Q4- Write a program to declare three classes .


Declare integer as data members in each class following encapsulation.
Perform addition of two data memeber arrays into array of this class.Use friend
function.*/

#include <iostream>

using namespace std;

class ClassB; // Forward declaration of ClassB


class ClassC; // Forward declaration of ClassC

class ClassA {
private:
int arrA[5]; // Private array to hold elements of Class A

public:
// Function to accept input for array A
void acceptArrayA() {
cout << "Enter 5 elements for array A: " << endl;
for (int i = 0; i < 5; i++) {
cout << "Element " << i + 1 << ": ";
cin >> arrA[i];
}
}

// Friend function to allow access to private members


friend void addArrays(ClassA &objA, ClassB &objB, ClassC &objC);
};

class ClassB {
private:
int arrB[5]; // Private array to hold elements of Class B

public:
// Function to accept input for array B
void acceptArrayB() {
cout << "Enter 5 elements for array B: " << endl;
for (int i = 0; i < 5; i++) {
cout << "Element " << i + 1 << ": ";
cin >> arrB[i];
}
}

// Friend function to allow access to private members


friend void addArrays(ClassA &objA, ClassB &objB, ClassC &objC);
};

class ClassC {
private:
int arrC[5]; // Private array to hold elements of Class C (the sum)

public:
// Function to display the elements of array C
void displayArrayC() {
cout << "Array C (sum of A and B): ";
for (int i = 0; i < 5; i++) {
cout << arrC[i] << " "; // Display each element of the result array
}
cout << endl;
}

// Friend function to allow access to private members


friend void addArrays(ClassA &objA, ClassB &objB, ClassC &objC);
};

// Friend function to add elements of arrays from Class A and Class B, and store
the result in Class C
void addArrays(ClassA &objA, ClassB &objB, ClassC &objC) {
for (int i = 0; i < 5; i++) {
objC.arrC[i] = objA.arrA[i] + objB.arrB[i]; // Add corresponding elements
of arrays A and B
}
}

int main() {
// Create objects of ClassA, ClassB, and ClassC
ClassA objA;
ClassB objB;
ClassC objC;

// Accept inputs for arrays A and B


objA.acceptArrayA();
objB.acceptArrayB();

// Perform addition of arrays A and B, storing the result in array C


addArrays(objA, objB, objC);

// Display the resulting array C


objC.displayArrayC();

return 0;
}
//ASSIGNMENT 6

/*Q1. Write a menu driven program in C++ to add or subtract integer values or
floatingpoint numbers.
Create a class named Add_Sub and overload member functions for doing the operations
on integer and float.
Accept first choice from the user to select add or subtract operation and
second choice to select integer or floating point numbers.
Use read only functions with 'const' keyword to display the result*/

#include <iostream> // Include the iostream library for input/output operations

using namespace std; // Use the standard namespace to avoid writing "std::" before
each input/output operation

// Class definition for Add_Sub


class Add_Sub {
private:
// Private member variables for storing integer and floating-point results
int num1, num2, result; // Variables for integer operations
float fnum1, fnum2, fresult; // Variables for floating-point operations

public:
// Function to add two integer numbers and store the result in 'result'
void addInt(int a, int b) {
result = a + b;
}

// Function to subtract two integer numbers and store the result in 'result'
void subInt(int a, int b) {
result = a - b;
}

// Function to add two floating-point numbers and store the result in 'fresult'
void addFloat(float a, float b) {
fresult = a + b;
}

// Function to subtract two floating-point numbers and store the result in


'fresult'
void subFloat(float a, float b) {
fresult = a - b;
}

// A 'const' function to display the integer result. The 'const' keyword


ensures that this function does not modify any class member variables.
void displayIntResult() const {
cout << "Integer Result: " << result << endl;
}

// A 'const' function to display the floating-point result. Again, the 'const'


keyword ensures that this function doesn't change any class data.
void displayFloatResult() const {
cout << "Floating-Point Result: " << fresult << endl;
}
};

int main() {
Add_Sub obj; // Create an object 'obj' of the Add_Sub class
int choice1, choice2; // Variables to store user's choices for operations and
data type
int num1, num2; // Variables to store integer values entered by the user
float fnum1, fnum2; // Variables to store floating-point values entered by the
user

// Display menu for the user to select the operation: Add or Subtract
cout << "Menu:\n";
cout << "1. Add\n";
cout << "2. Subtract\n";
cout << "Enter your choice: ";
cin >> choice1; // Store the user's choice in 'choice1'

// Ask the user to select the data type: Integer or Floating-Point


cout << "Select data type:\n";
cout << "1. Integer\n";
cout << "2. Floating-Point\n";
cout << "Enter your choice: ";
cin >> choice2; // Store the user's choice in 'choice2'

// Based on the user's choice for data type, perform the corresponding
operations
if (choice2 == 1) { // If the user selects 'Integer'
cout << "Enter two integer values: ";
cin >> num1 >> num2; // Input two integer values

if (choice1 == 1) { // If the user selected 'Add' as the operation


obj.addInt(num1, num2); // Call the addInt function to add the two
integers
} else { // If the user selected 'Subtract' as the operation
obj.subInt(num1, num2); // Call the subInt function to subtract the
two integers
}

obj.displayIntResult(); // Display the result of the integer operation

} else if (choice2 == 2) { // If the user selects 'Floating-Point'


cout << "Enter two floating-point values: ";
cin >> fnum1 >> fnum2; // Input two floating-point values

if (choice1 == 1) { // If the user selected 'Add' as the operation


obj.addFloat(fnum1, fnum2); // Call the addFloat function to add the
two floats
} else { // If the user selected 'Subtract' as the operation
obj.subFloat(fnum1, fnum2); // Call the subFloat function to subtract
the two floats
}

obj.displayFloatResult(); // Display the result of the floating-point


operation

} else {
// If the user enters an invalid choice for data type
cout << "Invalid choice!\n";
}
return 0; // Return 0 to indicate successful execution of the program
}

/*Q2-. Enhance the Q1 to implement all arithmetic operations (+,-,*,/. %) of a


calculator for both (integer and float). Use read only functions to display the
result.
The program should continue to run until the user enters 'x' to exit.*/

#include <iostream>

using namespace std;

class Calculator {
private:
int num1, num2, result;
float fnum1, fnum2, fresult;

public:
void addInt(int a, int b) {
result = a + b;
}

void subInt(int a, int b) {


result = a - b;
}

void mulInt(int a, int b) {


result = a * b;
}

void divInt(int a, int b) {


if (b == 0) {
cout << "Error: Division by zero\n";
return;
}
result = a / b;
}

void modInt(int a, int b) {


if (b == 0) {
cout << "Error: Division by zero\n";
return;
}
result = a % b;
}

void addFloat(float a, float b) {


fresult = a + b;
}

void subFloat(float a, float b) {


fresult = a - b;
}
void mulFloat(float a, float b) {
fresult = a * b;
}

void divFloat(float a, float b) {


if (b == 0) {
cout << "Error: Division by zero\n";
return;
}
fresult = a / b;
}

void displayIntResult() const {


cout << "Integer Result: " << result << endl;
}

void displayFloatResult() const {


cout << "Floating-Point Result: " << fresult << endl;
}
};

int main() {
Calculator obj;
char choice, op;
int num1, num2;
float fnum1, fnum2;

do {
cout << "Menu:\n";
cout << "1. Add\n";
cout << "2. Subtract\n";
cout << "3. Multiply\n";
cout << "4. Divide\n";
cout << "5. Modulus (integer only)\n";
cout << "Enter your choice: ";
cin >> choice;

cout << "Select data type:\n";


cout << "1. Integer\n";
cout << "2. Floating-Point\n";
cout << "Enter your choice: ";
cin >> op;

if (op == '1') {
cout << "Enter two integer values: ";
cin >> num1 >> num2;

switch (choice) {
case '1':
obj.addInt(num1, num2);
break;
case '2':
obj.subInt(num1, num2);
break;
case '3':
obj.mulInt(num1, num2);
break;
case '4':
obj.divInt(num1, num2);
break;
case '5':
obj.modInt(num1, num2);
break;
default:
cout << "Invalid choice!\n";
}

obj.displayIntResult();
} else if (op == '2') {
cout << "Enter two floating-point values: ";
cin >> fnum1 >> fnum2;

switch (choice) {
case '1':
obj.addFloat(fnum1, fnum2);
break;
case '2':
obj.subFloat(fnum1, fnum2);
break;
case '3':
obj.mulFloat(fnum1, fnum2);
break;
case '4':
obj.divFloat(fnum1, fnum2);
break;
default:
cout << "Invalid choice!\n";
}

obj.displayFloatResult();
} else {
cout << "Invalid choice!\n";
}

cout << "Enter 'x' to exit, any other key to continue: ";
cin >> choice;
} while (choice != 'x');

return 0;
}

//ASSIGNMENT 7
(Constructor overloading)
/*
Q1.Write a program to input two numbers through parameterized constructor and
display.*/
#include<iostream>
using namespace std;

class NumberPair // A class named 'NumberPair' is created


{
// Private members of the class (these cannot be accessed outside the class
directly)
private:
int num1; // Variable to store the first number
int num2; // Variable to store the second number

// Public members of the class (these can be accessed outside the class)
public:
// Constructor: A special function that gets called automatically when an
object of this class is created
// This is a parameterized constructor, meaning it takes two arguments (int
a, int b)
NumberPair(int a, int b) : num1(a), num2(b)
{
// This syntax in the constructor is called the initialization list
// It assigns the values of 'a' and 'b' to the member variables 'num1'
and 'num2' respectively
}

// Member function to display the values of num1 and num2


void display() const // The 'const' keyword indicates that this function
doesn't modify any member variables
{
cout << "Number 1: " << num1 << endl; // Output the value of num1
cout << "Number 2: " << num2 << endl; // Output the value of num2
}
};

int main() // The main function, where the program starts executing
{
int a, b; // Declare two integer variables 'a' and 'b'

// Ask the user to input two numbers


cout << "Enter two numbers:\n";
cin >> a >> b; // Read the values for 'a' and 'b' from the user

// Create an object of the 'NumberPair' class, passing 'a' and 'b' to the
constructor
// This automatically calls the constructor and assigns the values of 'a' and
'b' to 'num1' and 'num2'
NumberPair pair(a, b);

// Call the 'display' function to print the values of 'num1' and 'num2'
pair.display();

return 0; // Return 0 to indicate the program ended successfully


}
/*2} Write a program in c++ for constructor overloading.
Also define a parameterised constructor with default values.*/

#include <iostream>
using namespace std;
class Rectangle
{
int width, height;
public:
Rectangle() : width(0), height(0) {}
Rectangle(int w, int h = 10) : width(w), height(h) {}

int area() { return width * height; }


};

int main()
{
Rectangle rect1,rect2(5),rect3(5,20);
cout << "Area of rect1:" << rect1.area() << endl;
cout << "Area of rect2:" << rect2.area() << endl;
cout << "Area of rect3:" << rect3.area() << endl;
return 0;
}

/*Q3. Define a rectangle class. Data members - Length and breadth as double type.
Include the following member function:
a)Constructor: Assigns default values (5 to length and 3 to breadth)
b)Display data members through a read only function
c)Calculate area
d)Calculate circumference
e)Read data members*/

#include <iostream>
using namespace std;

class Rectangle {
// Private data members to store the dimensions of the rectangle
double length, breadth;

public:
// Constructor: Initializes length to 5 and breadth to 3 by default
Rectangle() : length(5), breadth(3) {}

// Function to read and set the values of length and breadth


void readData(double l, double b) {
length = l; // Assign the given value to length
breadth = b; // Assign the given value to breadth
}

// Read-only function to display the current values of length and breadth


void display() const {
// Note: There was a typo in your original code; it should be '<<' for
output
cout << "Length: " << length << ". Breadth: " << breadth << endl;
}

// Function to calculate the area of the rectangle


// Formula for area: length * breadth
double area() const {
return length * breadth;
}

// Function to calculate the circumference (or perimeter) of the rectangle


// Formula for circumference: 2 * (length + breadth)
double circumference() const {
return 2 * (length + breadth);
}
};

int main() {
// Create an object 'rect' of class Rectangle, initialized with default values
Rectangle rect;

// Display the default length and breadth values (length = 5, breadth = 3)


rect.display();

// Calculate and display the area and circumference using default values
cout << "Area: " << rect.area() << endl;
cout << "Circumference: " << rect.circumference() << endl;

// Modify the length and breadth using the readData function


rect.readData(10, 7); // Sets length = 10 and breadth = 7

// Display the updated length and breadth values


rect.display();

// Calculate and display the updated area and circumference


cout << "Area: " << rect.area() << endl;
cout << "Circumference: " << rect.circumference() << endl;

return 0;
}

//Q4.Write a program to add two complex number. Show the use of constructor
overloading.

#include<iostream>
using namespace std;

class complex {
// These are private data members that store the real and imaginary parts of a
complex number
int real;
int imag;

public:
// Function to display the complex number
void show() {
// Print the real part first
cout << real;

// If the imaginary part is positive, print a '+' sign for proper


formatting
if (imag > 0)
cout << "+";

// Print the imaginary part followed by 'i' to indicate it's imaginary


cout << imag << "i" << endl;
}

// Constructor with default values for real and imaginary parts


// This allows you to create objects with or without initial values
complex(int r = 0, int i = 0) {
real = r; // Initialize the real part
imag = i; // Initialize the imaginary part
}

// Function to add two complex numbers


// It takes another complex number object as a parameter
complex addcomplex(complex c) {
complex t; // Create a temporary complex object to hold the result

// Add the real parts and assign the result to the real part of 't'
t.real = real + c.real;

// Add the imaginary parts and assign the result to the imaginary part
of 't'
t.imag = imag + c.imag;

// Return the resulting complex number 't'


return t;
}
};

int main() {
// Create two complex numbers using the constructor
// c1 is initialized to 2 + (-5)i and c2 is initialized to -3 + 4i
complex c1(2, -5);
complex c2(-3, 4);

// Display the first complex number (c1)


c1.show();

// Display the second complex number (c2)


c2.show();

// Create a third complex number (c3) that will hold the sum of c1 and c2
complex c3;

// Add c1 and c2 and store the result in c3


c3 = c1.addcomplex(c2); // Notice: 'C3' should be 'c3' (fix the typo)

// Display the result (c3), which is the sum of c1 and c2


c3.show();
return 0; // End the program
}

// Assignment – 8
(Constructor)

/*Define a class stack that has member variables- an array of integers, size of the
array, stack top.
Implement the functionality of a stack using the follow member functions:
1. Constructor (initializes all array elements to zero)
2. Display the stack
3. Pop
4. Push*/

#include<iostream>
using namespace std;

// Define a class Stack to implement a stack using an array


class Stack {
private:
int *arr; // Pointer to dynamically allocate memory for the stack
int size; // Size of the stack
int top; // Index of the top element in the stack

public:
// Constructor to initialize the stack
Stack(int s) {
size = s; // Set the size of the stack
arr = new int[size]; // Allocate memory for the stack array
top = -1; // Initialize top to -1 (indicating the stack is
empty)
// Initialize all array elements to zero
for(int i = 0; i < size; i++) {
arr[i] = 0;
}
}

// Function to display elements of the stack


void display() {
if (top == -1) { // If the stack is empty
cout << "Stack is empty" << endl;
} else {
// Print elements from the top of the stack to the bottom
for (int i = top; i >= 0; i--) {
cout << arr[i] << " ";
}
cout << endl;
}
}

// Function to push (insert) an element into the stack


void push(int x) {
if (top == size - 1) { // Check if the stack is full
cout << "Stack is full" << endl;
} else {
top++; // Move top to the next position
arr[top] = x; // Insert the new element at the top position
}
}

// Function to pop (remove) an element from the stack


void pop() {
if (top == -1) { // If the stack is empty
cout << "Stack is empty" << endl;
} else {
cout << "Popped number is: " << arr[top] << endl; // Display the
element to be popped
top--; // Move top to the previous position (removing the top
element)
}
}
};

int main() {
int y, ch, num;

// Ask the user for the size of the stack


cout << "Enter Stack size" << endl;
cin >> y;

// Create a stack object with the given size


Stack s(y);

// Infinite loop to keep showing options to the user


while (1) {
cout << "Enter your choice: 1.push 2.pop 3.display 4.exit" << endl;
cin >> ch;

switch (ch) {
case 1:
// Push operation
cout << "Enter number to push into Stack" << endl;
cin >> num;
s.push(num);
break;

case 2:
// Pop operation
s.pop();
break;

case 3:
// Display the current stack
s.display();
break;

case 4:
// Exit the program
exit(0);
}
}
return 0;
}

/*Q2. Write a program to join two Strings using constructor.


Declare the <string> header.
Create objects of thestring class to concatenate using the constructor*/

#include<iostream> // Including the input-output stream library to use 'cin' and


'cout'
using namespace std;

class stringjoin { // Defining a class named 'stringjoin'


public:
string joinedstring; // Public member variable of type string to hold the
joined string

// Constructor of the class 'stringjoin' that takes two strings as


parameters
stringjoin(string str1, string str2) {
// The constructor is used to concatenate (join) the two strings 'str1'
and 'str2'
joinedstring = str1 + str2; // '+' operator is used to concatenate two
strings
}
};

int main() {
// Declaring and initializing two string variables
string str1 = "Hello "; // First string with the value "Hello "
string str2 = "Hiii"; // Second string with the value "Hiii"

// Creating an object 'joined' of class 'stringjoin' and passing 'str1' and


'str2' to the constructor
stringjoin joined(str1, str2);

// Printing the joined string, which was created in the constructor


cout << joined.joinedstring << endl;

return 0; // End of the program


}

/*Q3. Write a program in c++ to create a class time(hour, minute and second) and
initialize the time through constructor. Define a
function to show the time in HH:MM:SS format. Define another function to welcome
the user by showing the
message Good Morning/Afternoon/Evening as per the time initialized through
constructor. Destroy the object
through destructor.*/

#include <iostream>
#include <iomanip> // Required for setting output formatting (setw, setfill)
using namespace std;

class Time {
private:
int hour, minute, second; // Member variables to store hours, minutes, and
seconds

public:
// Constructor to initialize the time
Time(int h, int m, int s) : hour(h), minute(m), second(s) {
// The constructor initializes the time with given values of hour, minute,
and second
}

// Function to display the time in HH:MM:SS format


void showTime() const {
// setw(2) ensures that each field has exactly two characters (e.g., '01'
instead of '1')
// setfill('0') ensures that '0' is used to pad the field if it is less
than 2 characters
cout << setw(2) << setfill('0') << hour << ":"
<< setw(2) << setfill('0') << minute << ":"
<< setw(2) << setfill('0') << second << endl;
// This prints the time in the desired HH:MM:SS format
}

// Function to display a greeting based on the time of day


void welcomeUser() const {
// Conditional statements determine which greeting to display
if (hour < 12) {
cout << "Good Morning!" << endl; // Before 12 PM
} else if (hour < 17) {
cout << "Good Afternoon!" << endl; // Between 12 PM and 5 PM
} else {
cout << "Good Evening!" << endl; // After 5 PM
}
// This function gives a greeting based on the hour of the day
}

// Destructor is called when an object of Time class is destroyed


~Time() {
cout << "Time object destroyed." << endl;
// The destructor simply prints a message when the object is destroyed
// This happens when the object goes out of scope or is explicitly deleted
}
};

int main() {
// Creating an instance of Time with hour 14 (2 PM), minute 30, and second 45
Time t(14, 30, 45); // This automatically calls the constructor

// Call the showTime function to display the time


t.showTime();

// Call the welcomeUser function to display the appropriate greeting


t.welcomeUser();

// After main function ends, the object 't' will be destroyed automatically
// This will call the destructor and print "Time object destroyed."
return 0;
}

/*Q4. Write a program in c++ to create a class Player having data members Player
ID, Player name and Game specification.
Copy one object of Player class to another object using copy constructor.*/

#include <iostream>
#include <cstring> // for strcpy and strlen

class Player {
private:
int playerID; // Data member to store the player's ID
char playerName[50]; // Data member to store the player's name (character
array)
char gameSpec[50]; // Data member to store the player's game
specification (character array)

public:
// Parameterized Constructor
Player(int id, const char* name, const char* game) : playerID(id) {
// Initialize playerID with the value passed in the constructor
// Copy the player's name and game specification using strcpy
strcpy(playerName, name); // Copies the string 'name' to 'playerName'
strcpy(gameSpec, game); // Copies the string 'game' to 'gameSpec'
}

// Copy Constructor: This constructor is called when an object is copied


Player(const Player& other) : playerID(other.playerID) {
// Copy the playerID from the other object to this object
strcpy(playerName, other.playerName); // Copy the playerName from the
'other' object to this object
strcpy(gameSpec, other.gameSpec); // Copy the gameSpec from the
'other' object to this object
}

// Function to display the player's information


void display() const {
// Display the player's ID, name, and game specification
std::cout << "Player ID: " << playerID << std::endl;
std::cout << "Player Name: " << playerName << std::endl;
std::cout << "Game Specification: " << gameSpec << std::endl;
}
};

int main() {
// Create an object 'p1' of class Player using the parameterized constructor
Player p1(1, "Madhav", "Soccer");

// Create another object 'p2' by copying 'p1' using the copy constructor
// This triggers the copy constructor and copies the data from p1 to p2
Player p2 = p1;
// Display the data of the first player
p1.display();

// Print a separator line


std::cout << "----" << std::endl;

// Display the data of the second player (which is a copy of p1)


p2.display();

return 0;
}

// Assignment – 9
// (Operator
Overloading)

/*Q1. Write a simple program to overload the increment operator. The increment
operator should increase the values of all the integer and floating-point data
members by 1.
For character data members the increment operator should update the value to the
next character.*/

#include <iostream>
using namespace std;

class MyClass {
private:
int intval;
float floatval;
char charval;

public:
// Constructor to initialize the values of the object
MyClass(int i, float f, char c) : intval(i), floatval(f), charval(c) {}

// Overloading the prefix increment operator


void operator++() {
intval++; // Increment integer value by 1
floatval++; // Increment float value by 1.0
charval++; // Increment character to the next character in ASCII
}

// Function to display the values of the data members


void display() const {
cout << "INT: " << intval << ", Float: " << floatval << ", Char: " <<
charval << endl;
}
};

int main() {
MyClass obj(10, 20.5, 'A'); // Creating an object with initial values
obj.display(); // Display initial values
++obj; // Using overloaded increment operator
obj.display(); // Display values after increment

return 0;
}

/*Q2. Write a program to concatenate two strings using operator overloading*/

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

class MyString {
private:
string str;

public:
// Constructor to initialize the string
MyString(string s) : str(s) {}

// Overloading the + operator for concatenating strings


MyString operator+(const MyString &other) {
return MyString(str + other.str); // Concatenates the two strings
}

// Function to display the string


void display() const {
cout << str << endl;
}
};

int main() {
MyString str1("Hello ");
MyString str2("World");

// Using overloaded + operator to concatenate strings


MyString result = str1 + str2;
result.display(); // Displaying the concatenated result

return 0;
}

/*Q3. Write a program to overload the binary + operator to perform addition of two
objects. The
operator function should add the integer and float values of the two objects and
store it in the
third object.*/

#include <iostream>
using namespace std;
class MyClass {
private:
int intval; // Integer data member
float floatval; // Float data member

public:
// Constructor to initialize integer and float values
MyClass(int i, float f) : intval(i), floatval(f) {}

// Overloading the + operator


MyClass operator+(const MyClass& other) {
// Creates a new MyClass object with the sum of the integer and float
values
return MyClass(intval + other.intval, floatval + other.floatval);
}

// Function to display the values of intval and floatval


void display() const {
cout << "INT: " << intval << ", Float: " << floatval << endl;
}
};

int main() {
// Create two MyClass objects with initial values
MyClass obj1(10, 20.5);
MyClass obj2(30, 40.5);

// Use the overloaded + operator to add obj1 and obj2, storing the result in a
new object
MyClass result = obj1 + obj2;

// Display the result


result.display();

return 0;
}

/*Q4. Write the program in Q3 to implement the operator overloading using friend
function.*/

#include <iostream>
using namespace std;

class MyClass {
private:
int intval; // Integer data member
float floatval; // Float data member

public:
// Constructor to initialize integer and float values
MyClass(int i, float f) : intval(i), floatval(f) {}

// Friend function to overload the + operator


friend MyClass operator+(const MyClass& obj1, const MyClass& obj2);
// Function to display the values of intval and floatval
void display() const {
cout << "INT: " << intval << ", Float: " << floatval << endl;
}
};

// Friend function to overload the + operator


// Accesses private members of MyClass objects obj1 and obj2 to add their values
MyClass operator+(const MyClass& obj1, const MyClass& obj2) {
// Creates and returns a new MyClass object with summed values
return MyClass(obj1.intval + obj2.intval, obj1.floatval + obj2.floatval);
}

int main() {
// Create two MyClass objects with initial values
MyClass obj1(10, 20.5);
MyClass obj2(30, 40.5);

// Use the overloaded + operator to add obj1 and obj2, storing the result in a
new object
MyClass result = obj1 + obj2;

// Display the result


result.display();

return 0;
}

ASSIGNMENT:-10

/Q1.*WAP for implementation of single inheritance. Create a class person (Name,


ID), inherited class Salary(designation, basic). Design appropriate member
functions
to accept data and calculate the TA = 35% of basic, DA = 60% of basic, HRA = 35% of
basic, PF = 12% of basic. Display the employee details with net and Gross salary*/

#include<iostream>
#include<string>
using namespace std;
//base class

class Person
{
protected:
string name;
int id;
public:
//constructor
Person(string n,int i)
{
name = n;
id = i;
}
Person()
{

}
void AcceptPersonDetails()
{
cout << "Enter name: ";
getline(cin, name);
cout << "Enter ID: ";
cin >> id;
cin.ignore();
}
void DisplayPersonDetails()
{
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
}
};
//salary class
class Salary : public Person
{
private:
string designation;
double basic;
double TA,DA,HRA,PF,GrossSalary,NetSalary;
public:
Salary(string d, double b, string n, int i) :Person(n,i)
{
designation = d;
basic = b;
}

void acceptSalaryDetails()
{
AcceptPersonDetails();
cout << "Enter Designation: ";
getline(cin,designation);

cout << "Enter Basic Salary: ";


cin >> basic;
calculation();
}
void calculation()
{
TA = 0.35 * basic;
DA = 0.6 * basic;
HRA = 0.35 * basic;
PF = 0.12 * basic;
GrossSalary = basic + TA + DA + HRA;
NetSalary = GrossSalary - PF;
}
void displaySalaryDetails()
{
DisplayPersonDetails();
cout << "Designation: " << designation << endl;
cout << "Basic Salary: " << basic << endl;
cout << "TA(35%): " << TA << endl;
cout << "DA(60%): " << DA << endl;
cout << "HRA(35%): " << HRA << endl;
cout << "PF(12%): " << PF << endl;
cout << "Gross Salary: " << GrossSalary << endl;
cout << "Net Salary: " << NetSalary << endl;
}
Salary(){}

};
int main()
{
Salary emp1;
emp1.acceptSalaryDetails();
cout << "\nEmployee Details: " << endl;
emp1.displaySalaryDetails();

Salary emp2("kuh",45000,"deepa",43);
emp2.calculation();
emp2.displaySalaryDetails();
return 0;
}

/Q2.*Implement the following form of ingeritance. Define required classeed, member


variables, member functions and constructors inside the classes. Acceppt all the
details
for a student from the user using appropriate member functio and print the details
along with the final CGPA and Crade dependind upon the marks scored. You may use
your won member functions.*/

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

class Person {
protected:
string name;
int age;
public:
// Constructor for Person class
Person(const string& n, int a) : name(n), age(a) {}

// Display function for personal details


void displayPersonDetails() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};

class Student : public Person {


private:
int rollNumber;
string branch;
double sgpa[6]; // Array to store SGPA of 6 semesters
double cgpa;
char grade;
public:
// Constructor for Student class, also initializes Person
Student(const string& n, int a, int roll, const string& br) : Person(n, a),
rollNumber(roll), branch(br) {}

// Function to accept SGPA details and calculate CGPA and grade


void acceptStudentDetails() {
cout << "Enter SGPA for 6 semesters:\n";
for (int i = 0; i < 6; i++) {
cout << "Semester " << i + 1 << ": ";
cin >> sgpa[i];
}
calculateCGPA();
determineGrade();
}

// Calculate CGPA based on SGPA array


void calculateCGPA() {
double totalSGPA = 0.0;
for (int i = 0; i < 6; i++) {
totalSGPA += sgpa[i];
}
cgpa = totalSGPA / 6;
}

// Determine grade based on CGPA


void determineGrade() {
if (cgpa >= 9.0) grade = 'A';
else if (cgpa >= 8.0) grade = 'B';
else if (cgpa >= 7.0) grade = 'C';
else if (cgpa >= 6.0) grade = 'D';
else grade = 'F';
}

// Display student details along with CGPA and grade


void displayStudentDetails() {
displayPersonDetails();
cout << "Roll Number: " << rollNumber << endl;
cout << "Branch: " << branch << endl;
for (int i = 0; i < 6; i++) {
cout << "SGPA for Semester " << i + 1 << ": " << sgpa[i] << endl;
}
cout << "CGPA: " << cgpa << endl;
cout << "Grade: " << grade << endl;
}
};

int main() {
// Create a student object with sample data
Student student("Madhav", 20, 38, "BCA");

// Accept SGPA details, calculate CGPA, and display all information


student.acceptStudentDetails();
cout << "\nStudent Details:\n";
student.displayStudentDetails();

return 0;
}
/*Q3. Implement the following type of inheritance. Create appropriate class,
datamembers and
member functions to accept the values from the user and display the student details
along
with the final grade depending upon the marks scored. */

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

class Student {
protected:
int roll;
string branch;
public:
// Constructor to accept student details
Student() {
cout << "Enter roll no: ";
cin >> roll;
cout << "Enter branch: ";
cin >> branch;
}
};

class MidSem : virtual public Student {


protected:
int theory_mark1;
int lab_mark1;
public:
// Constructor to accept mid-sem marks
MidSem() {
cout << "Enter Mid Sem Theory marks out of 20: ";
cin >> theory_mark1;
cout << "Enter Mid Sem Lab marks out of 10: ";
cin >> lab_mark1;
}
};

class EndSem : virtual public Student {


protected:
int theory_mark2;
int lab_mark2;
public:
// Constructor to accept end-sem marks
EndSem() {
cout << "Enter End Sem Theory marks out of 50: ";
cin >> theory_mark2;
cout << "Enter End Sem Lab marks out of 20: ";
cin >> lab_mark2;
}
};

class Result : public MidSem, public EndSem {


private:
int total_theory;
int total_lab;
char grade;

// Function to calculate grade based on total marks


char calculateGrade() {
int total = (total_theory + total_lab) / 10;
if (total >= 9) return 'O';
else if (total >= 8) return 'A';
else if (total >= 7) return 'B';
else if (total >= 5) return 'C';
else return 'F';
}

public:
// Constructor to calculate total marks and determine grade
Result() {
total_theory = theory_mark1 + theory_mark2;
total_lab = lab_mark1 + lab_mark2;
grade = calculateGrade();
}

// Display final result


void display() {
cout << "\nStudent Final Grade Report\n";
cout << "Roll No: " << roll << endl;
cout << "Branch: " << branch << endl;
cout << "Total Theory Marks: " << total_theory << endl;
cout << "Total Lab Marks: " << total_lab << endl;
cout << "Grade: " << grade << endl;
}
};

int main() {
// Create Result object and display student result
Result studentResult;
studentResult.display();
return 0;
}

ASSIGNMENT:-11

/*Q1.Create a class Person(Name, ID, designation), inherited class Account(salary),


HR(experience in years). Ingerit another class Position(Grade) from account and HR
which will calculate the grade as follows:
a. Salary > 50000 & exp >= 10 years grade = A
b. Salary > 40000 & exp >= 5 years grade = B
a. Salary > 25000 & exp >= 3 years grade = C
a. Salary > 20000 & exp < 3 years grade = D
Accept the employee through member functin and display the employee details along
with the grade*/

#include<iostream>
#include<string>
using namespace std;
class Person
{
protected:
string name;
int id;
string designation;
public:
void Accept_Person_Details()
{
cout << "Enter Name: ";
getline(cin,name);

cout << "Enter ID: ";


cin >> id;

cout << "Enter designation: ";


cin.ignore();
getline(cin,designation);
}
void displayPersonDetails()
{
cout << "Name: " << name << endl;
cout << "ID: " << id << endl;
cout << "Designation: " << designation << endl;
}
};

class Account :virtual public Person


{
protected:
double salary;
public:
void Accept_Account_Details()
{
cout << "Enter Salary: ";
cin >> salary;
}

void displayAccountDetails()
{
cout << "Salary: " << salary << endl;
}
};

class HR : virtual public Person


{
protected:
int experience;
public:
void Accept_HR_Details()
{
cout << "Enter Experience in years: ";
cin >> experience;
}

void displayHRDetails() const


{
cout << "Experience: " << experience << endl;
}
};
class Position : public Account, public HR
{
private:
char grade;
public:
void calculate_Grade()
{
if(salary > 50000 && experience >= 10) grade = 'A';
else if(salary > 40000 && experience >= 5) grade = 'B';
else if(salary > 25000 && experience >= 3) grade = 'C';
else if(salary > 20000 && experience < 3) grade = 'D';
else grade = 'E';
}

void Accept_Details()
{
Accept_Person_Details();
Accept_Account_Details();
Accept_HR_Details();
calculate_Grade();
}
void Display_Details()
{
displayPersonDetails();
displayAccountDetails();
displayHRDetails();
cout << "Grade: " << grade << endl;
}
};

int main()
{
Position emp;
emp.Accept_Details();
cout << "\nEmployee Details: " << endl;
emp.Display_Details();
return 0;
}

/*Q2.Create a class Book(BName,Bid), ingerited class BookDetail(Author,


no_of_pages,type), Price(Actual_price, Discount_price), ingerit the class
Region(country) from the
BookDetail and Price classes, if the country is India, then price is actual price
and for others discounted price should be displayed in the display member function
of
the Print class which inherits from Region class, Accept the values of the
attribute from the user and display the book details including the price.*/

#include<iostream>
#include<string>
using namespace std;
class Book
{
protected:
string BName;
int Bid;
public:
void Accept_Book_Details()
{
cout << "Enter Book Name: ";
getline(cin,BName);

cout << "Enter ID: ";


cin >> Bid;
}
void displayBookDetails()
{
cout << "Book Name: " << BName << endl;
cout << "Book ID: " << Bid << endl;
}
};

class BookDetail :virtual public Book


{
protected:
string Author;
int no_of_pages;
string type;
public:
void Accept_BookDetails()
{
cin.ignore();
cout << "Enter Author: ";
getline(cin,Author);

cout << "Enter Number of pages: ";


cin >> no_of_pages;
cin.ignore();

cout << "Enter Book types: ";


getline(cin,type);
}

void displayBookDetails()
{
cout << "Author: " << Author << endl;
cout << "Number of Pages: " << no_of_pages << endl;
cout << "Type: " << type << endl;
}
};
class Price : virtual public Book
{
protected:
double Actual_price;
double Discount_price;
public:
void Accept_Price_Details()
{
cout << "Enter Actual price: ";
cin >> Actual_price;

cout << "Enter Discount Price: ";


cin >> Discount_price;
}

void displayPriceDetails()
{
cout << "Actual price: " << Actual_price << endl;
cout << "Discount Price: " << Discount_price << endl;
}
};
class Region : public BookDetail, public Price
{
protected:
string country;
public:
void Accept_Region_Details()
{
cin.ignore();
cout << "Enter Country: ";
getline(cin,country);
}

void displayRegionDetails() const


{
cout << "Country: " << country << endl;
}
};

class Print : public Region


{
public:
void Accept_Details()
{
Accept_Book_Details();
Accept_BookDetails();
Accept_Price_Details();
Accept_Region_Details();
}
void Display_Details()
{
displayBookDetails();
displayBookDetails();
displayPriceDetails();
displayRegionDetails();

cout << "Final Price: ";


if(country == "India" || country == "india")
{
cout << Actual_price << "(Actual Price)" << endl;
}
else
{
cout << Discount_price << "(Discounted Price)" << endl;
}
}
};
int main()
{
Print book;
book.Accept_Details();
cout << "\nBook Details: " << endl;
book.Display_Details();
return 0;
}

/*Q3: A bank maintains two kinds of accounts for customers, savings and current
account. The savings account provides compound interest and withdrawal facility,
check
book facility. Current account provides check book facility but no interest.Current
account holders should maintain a minimum balance of Rs. 100/-. Write a program to
create a class account that stores customer name account number and account type.
From this derive two classes curr_act for current account, save_act for savings
account.
include necessary member functions to accept required data through constructor and
performing transactions and to check the balance*/

#include<iostream>
#include<string>
#include<cmath>
using namespace std;
class Account
{
protected:
string customer_name;
int account_number;
string account_type;
double balance;
public:
//constructor to initialize common account details
Account(string name, int acc_num, string type, double initial_balance)
{
customer_name = name;
account_number = acc_num;
account_type = type;
balance = initial_balance;
}

void display_Details() const


{
cout << "Customer Name: " << customer_name << endl;
cout << "Account Number: " << account_number << endl;
cout << "Accoutn Type: " << account_type << endl;
cout << "Current Balance : " << balance << endl;
}
};

class Curr_Act : public Account


{
private:
const double minimum_balance = 100.0;
public:
Curr_Act(string name, int acc_num, double initial_balance) :
Account(name, acc_num, "Current", initial_balance){}
void withdraw(double amount)
{
if(balance - amount < minimum_balance)
{
cout << "Withdrawal denied Balance should not fall below
Rs. " << minimum_balance << endl;
}
else
{
balance -= amount;
cout << "Withdrawal successful! New balance is Rs. " <<
balance << endl;
}
}

void deposit(double amount)


{
balance += amount;
cout << "Deposit successful! New balance is Rs. " << balance <<
endl;
}
};

class Save_Act : public Account


{
private:
double interest_rate;
public:
Save_Act(string name, int acc_num, double initial_balance, double rate)
: Account(name, acc_num, "Saving", initial_balance), interest_rate(rate){}
void calculate_Interest(int years)
{
double amount = balance * pow((1 + interest_rate / 100), years);
double interest = amount - balance;
balance = amount;
cout << "Interest for " << years << "years is Rs. " << interest
<< endl;
cout << "New balance after adding interest is Rs. " << balance <<
endl;
}
void withdraw(double amount)
{
if(balance < amount)
{
cout << "Insufficien balance!" << endl;
}
else
{
balance += amount;
cout << "Deposit successful! New balance is Rs. " <<
balance << endl;
}
}
void deposit(double amount)
{
balance += amount;
cout << "Deposit successful! New balance is Rs. " << balance <<
endl;
}
};
int main()
{
Curr_Act current_account("Subhashree", 101, 500.0);
current_account.display_Details();
current_account.deposit(200);
current_account.withdraw(150);
current_account.withdraw(600);

cout << "------------------------" << endl;

Save_Act savings_account("deepa",102,1000.0,5.0);
savings_account.display_Details();
savings_account.deposit(300);
savings_account.withdraw(200);
savings_account.calculate_Interest(2);
return 0;
}

// Assignment-12 (Polymorphism)

/*Q1. Write a program to create a class named figure which should have one member
function
to compute the area of the figure and one member variable to store the area value.
Derive
two classes rectangle and triangle to accept (length, breadth) and (base, height).
Calculate area of two figures.
Make the base class function to compute the area a virtual function
and redefine it in the derived classes. Use pointer to base class concept.
--> Add required functions to compute the perimeter in the similar way the area is
calculated.
--> Compare the perimeter of both figures.
--> Compare the area of both figures.*/

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

class Figure {
protected:
double area;
public:
virtual double computeArea() = 0;
virtual double computePerimeter() = 0;
virtual ~Figure() {} // Virtual destructor
};

class Rectangle : public Figure {


public:
Rectangle(double length, double breadth) : length(length), breadth(breadth) {}

double computeArea() {
area = length * breadth;
return area;
}

double computePerimeter() {
return 2 * (length + breadth);
}

private:
double length, breadth;
};

class Triangle : public Figure {


public:
Triangle(double base, double height) : base(base), height(height) {}

double computeArea() {
area = 0.5 * base * height;
return area;
}

double computePerimeter() {
return base + height + sqrt(base * base + height * height); // Assuming
it's a right triangle
}

private:
double base, height;
};

int main() {
Figure* figure1 = new Rectangle(5, 3);
Figure* figure2 = new Triangle(4, 3);

if (figure1->computePerimeter() > figure2->computePerimeter()) {


cout << "Rectangle has a larger perimeter.\n";
} else if (figure1->computePerimeter() < figure2->computePerimeter()) {
cout << "Triangle has a larger perimeter.\n";
} else {
cout << "Both figures have the same perimeter.\n";
}

if (figure1->computeArea() > figure2->computeArea()) {


cout << "Rectangle has a larger area.\n";
} else if (figure1->computeArea() < figure2->computeArea()) {
cout << "Triangle has a larger area.\n";
} else {
cout << "Both figures have the same area.\n";
}

delete figure1;
delete figure2;

return 0;
}

// Assignment-13(Polymorphism)

/*Q1. Write a program to accept two numbers in the base class through constructor.
Derive two classes square and cube to calculate the sum of their squares and cubes.
Use appropriate constructor to accept the number and display function to display
the result.
Use the concepts of dynamic polymorphism.*/

#include <iostream>
using namespace std;

class Number {
protected:
double num1, num2;
public:
Number(double n1, double n2) : num1(n1), num2(n2) {}
virtual void compute() = 0; // Pure virtual function for computation
virtual void display() = 0; // Pure virtual function for display
virtual ~Number() {} // Virtual destructor
};

class Square : public Number {


private:
double sumOfSquare;
public:
Square(double n1, double n2) : Number(n1, n2), sumOfSquare(0) {}

void compute() { // Removed override


sumOfSquare = (num1 * num1) + (num2 * num2);
}

void display() { // Removed override


cout << "Sum of squares: " << sumOfSquare << endl;
}
};

class Cube : public Number {


private:
double sumOfCube;
public:
Cube(double n1, double n2) : Number(n1, n2), sumOfCube(0) {}

void compute() { // Removed override


sumOfCube = (num1 * num1 * num1) + (num2 * num2 * num2);
}

void display() { // Removed override


cout << "Sum of cubes: " << sumOfCube << endl;
}
};

int main() {
double num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;

Number* squareCalc = new Square(num1, num2);


Number* cubeCalc = new Cube(num1, num2);

squareCalc->compute();
squareCalc->display();

cubeCalc->compute();
cubeCalc->display();
delete squareCalc;
delete cubeCalc;

return 0;
}

/*Q2. Prove that the objects of a class containing virtual functions are larger in
size by 1 byte to
store the address of the virtual table. Write a program using virtual function to
demonstrate the same.*/

#include <iostream>
using namespace std;

class BaseNotVirtual {
public:
int a;
double b;
};

class BaseVirtual {
public:
int a;
double b;
virtual void func() {}
};

int main() {
BaseNotVirtual obj1;
BaseVirtual obj2;

cout << "Size of object without virtual function: " << sizeof(obj1) << " bytes"
<< endl;
cout << "Size of object with virtual function: " << sizeof(obj2) << " bytes" <<
endl;

return 0;
}

You might also like