0% found this document useful (0 votes)
25 views65 pages

Sodapdf

Uploaded by

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

Sodapdf

Uploaded by

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

1.Describe any three control structures in detail.

1. If-Else Statement
The if-else statement is a conditional control structure that allows the program to execute different blocks
of code based on a condition
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
2. Switch Statement
The switch statement is a control structure that allows the program to execute different blocks of code
based on the value of an expression.
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
...
default:
// code to be executed if expression does not match any case
break;
}
3. While Loop
The while loop is a control structure that allows the program to execute a block of code repeatedly while a
condition is true. The syntax is as follows:
while (condition) {
// code to be executed
}
2. Explain various data types used in C++
1. Integer Types
int: A 32-bit signed integer.
unsigned int: A 32-bit unsigned integer.
short int: A 16-bit signed integer.
unsigned short int: A 16-bit unsigned integer.
long int: A 64-bit signed integer.
unsigned long int: A 64-bit unsigned integer.
long long int: A 64-bit signed integer
unsigned long long int: A 64-bit unsigned integer
2. Floating-Point Types
float: A 32-bit floating-point number.
double: A 64-bit floating-point number.
long double: A 128-bit floating-point number
3. Character Types
char: A single character.
wchar_t: A wide character (used for Unicode characters).
3. Character Types
char: A single character.
wchar_t: A wide character (used for Unicode characters).
4. Boolean Type
bool: A boolean value (true or false)
5. Enumerated Types
enum: An enumeration is a set of named values.
6. Class and Struct Types
class: A user-defined data type that represents a blueprint for creating objects.
struct: A user-defined data type that represents a collection of variables.
7. Array Types
array: A collection of elements of the same data type.
8. Pointer Types
pointer: A variable that holds the memory address of another variable.
9. Union Types
union: A user-defined data type that allows storing different data types in the same memory location
10. Typedef
typedef: A keyword used to create an alias for an existing data type.
3.Describe various operators used in C++
C++ Operators
C++ divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
1.Arithmetic Operators
Addition (+)
The addition operator is used to add two or more values.

Example: a + b
2. Subtraction (-)

The subtraction operator - is used to subtract one number from another.

Example: a - b

3. Multiplication (*)

The multiplication operator * is used to multiply two or more numbers.

Example: a * b
4. Division (/)

The division operator / is used to divide one number by another.

Example: a / b

Note: When both operands are integers, the result is an integer (integer division). If one or both operands
are floating-point numbers, the result is a floating-point number.

5. Modulus (%)

The modulus operator % is used to find the remainder of an integer division.

Example: a % b
2.assignment operators
1. Simple Assignment (=)

The simple assignment operator = is used to assign a value to a variable.

Example: a = 5
2. Addition Assignment (+=)

The addition assignment operator += is used to add a value to a variable and assign the result back to the
variable.

Example: a += 5 is equivalent to a = a + 5
3. Subtraction Assignment (-=)

The subtraction assignment operator -= is used to subtract a value from a variable and assign the result
back to the variable.

Example: a -= 5 is equivalent to a = a - 5

4. Multiplication Assignment (*=)

The multiplication assignment operator *= is used to multiply a variable by a value and assign the result
back to the variable.

Example: a *= 5 is equivalent to a = a * 5
5. Division Assignment (/=)

The division assignment operator /= is used to divide a variable by a value and assign the result back to
the variable.

Example: a /= 5 is equivalent to a = a / 5

6. Modulus Assignment (%=)

The modulus assignment operator %= is used to find the remainder of a variable divided by a value and
assign the result back to the variable.

Example: a %= 5 is equivalent to a = a % 5
7. Bitwise AND Assignment (&=)

The bitwise AND assignment operator &= is used to perform a bitwise AND operation on a variable and a
value, and assign the result back to the variable.

Example: a &= 5 is equivalent to a = a & 5

8. Bitwise OR Assignment (|=)

The bitwise OR assignment operator |= is used to perform a bitwise OR operation on a variable and a
value, and assign the result back to the variable.

Example: a |= 5 is equivalent to a = a | 5
9. Bitwise XOR Assignment (^=)

The bitwise XOR assignment operator ^= is used to perform a bitwise XOR operation on a variable and a
value, and assign the result back to the variable.

Example: a ^= 5 is equivalent to a = a ^ 5

10. Left Shift Assignment (<<=)

The left shift assignment operator <<= is used to shift the bits of a variable to the left by a specified
number of positions and assign the result back to the variable.

Example: a <<= 2 is equivalent to a = a << 2


11. Right Shift Assignment (>>=)

The right shift assignment operator >>= is used to shift the bits of a variable to the right by a specified
number of positions and assign the result back to the variable.

Example: a >>= 2 is equivalent to a = a >> 2

2.comparison operators:
1. Equal To (==)

The equal to operator == returns true if both operands are equal.

Example: a == b
2. Not Equal To (!=)

The not equal to operator != returns true if both operands are not equal.

Example: a != b
3. Greater Than (>)

The greater than operator > returns true if the left operand is greater than the right operand.

Example: a > b
4. Less Than (<)

The less than operator < returns true if the left operand is less than the right operand.

Example: a < b
5. Greater Than or Equal To (>=)

The greater than or equal to operator >= returns true if the left operand is greater than or equal to the right
operand.

Example: a >= b
6. Less Than or Equal To (<=)

The less than or equal to operator <= returns true if the left operand is less than or equal to the right
operand.

Example: a <= b
logical operators:
1. Logical AND (&&)

The logical AND operator && returns true if both operands are true.

Example: a && b
2. Logical OR (||)

The logical OR operator || returns true if at least one operand is true.

Example: a || b
3. Logical NOT (!)
The logical NOT operator ! returns the opposite of the operand.

Example: !a

4.Demonstrate a C++ program using inline function.


#include <iostream>
using namespace std;

class Operation {
private:
int a, b, add, sub, mul;
float div;

public:
inline void get() {
cout << "Enter two numbers: ";
cin >> a >> b;
}

inline void sum() {


add = a + b;
}

inline void difference() {


sub = a - b;
}

inline void product() {


mul = a * b;
}

inline void division() {


if (b != 0)
div = (float)a / b;
else
cout << "Error! Division by zero is not allowed." << endl;
}

inline void display() {


cout << "Addition of two numbers: " << add << endl;
cout << "Difference of two numbers: " << sub << endl;
cout << "Product of two numbers: " << mul << endl;
cout << "Division of two numbers: " << div << endl;
}
};

int main() {
Operation op;
op.get();
op.sum();
op.difference();
op.product();
op.division();
op.display();
return 0;
}
5. Demonstrate a C++ program using Function overloading.
#include <iostream>

// Overload the add function for two integers


int add(int a, int b) {
return a + b;
}

// Overload the add function for two doubles


double add(double a, double b) {
return a + b;
}

int main() {
int num1 = 5;
int num2 = 7;
double num3 = 3.5;
double num4 = 6.2;
// Call the overloaded add function for two integers
std::cout << "The sum of " << num1 << " and " << num2 << " is: " << add(num1, num2) << std::endl;

// Call the overloaded add function for two doubles


std::cout << "The sum of " << num3 << " and " << num4 << " is: " << add(num3, num4) << std::endl;

return 0;
}

MODULE 2:
1. Demonstrate a C++ program using new and delete operator.#include <iostream>
using namespace std;

int main() {
// Using new to allocate memory for an integer
int* pInt = new int;
*pInt = 10;
cout << "Value of pInt: " << *pInt << endl;

// Using delete to deallocate memory for an integer


delete pInt;
cout << "Memory for pInt deallocated." << endl;

// Using new to allocate memory for an array of integers


int* pIntArray = new int[5];
for (int i = 0; i < 5; i++) {
pIntArray[i] = i * 2;
}
cout << "Values of pIntArray: ";
for (int i = 0; i < 5; i++) {
cout << pIntArray[i] << " ";
}
cout << endl;
// Using delete[] to deallocate memory for an array of integers
delete[] pIntArray;
cout << "Memory for pIntArray deallocated." << endl;

return 0;
}
2.Demonstrate a C++ program using pointers.
#include <iostream>
using namespace std;

int main() {
// Pointer to an integer
int x = 10;
int* px = &x;

// Accessing the value of x through the pointer


cout << "Value of x: " << x << endl;
cout << "Value of x through pointer: " << *px << endl;

// Pointer to an array of integers


int arr[5] = {1, 2, 3, 4, 5};
int* parr = arr;

// Accessing the elements of the array through the pointer


cout << "Array elements: ";
for (int i = 0; i < 5; i++) {
cout << parr[i] << " ";
}
cout << endl;

// Pointer arithmetic
cout << "Value of *(parr + 2): " << *(parr + 2) << endl;
cout << "Value of parr[2]: " << parr[2] << endl;

// Pointer to a pointer
int y = 20;
int* py = &y;
int** ppy = &py;

// Accessing the value of y through the double pointer


cout << "Value of y: " << y << endl;
cout << "Value of y through double pointer: " << **ppy << endl;

return 0;
}

MODULE3:
1. Demonstrate a C++ program using Constructors.

#include <iostream>
using namespace std;

class Rectangle {
private:
int width;
int height;

public:
// Default constructor
Rectangle() {
width = 0;
height = 0;
cout << "Default constructor called." << endl;
}

// Parameterized constructor
Rectangle(int w, int h) {
width = w;
height = h;
cout << "Parameterized constructor called." << endl;
}

// Copy constructor
Rectangle(const Rectangle& rect) {
width = rect.width;
height = rect.height;
cout << "Copy constructor called." << endl;
}

// Destructor
~Rectangle() {
cout << "Destructor called." << endl;
}

void display() {
cout << "Width: " << width << ", Height: " << height << endl;
}
};

int main() {
// Creating an object using default constructor
Rectangle rect1;
rect1.display();

// Creating an object using parameterized constructor


Rectangle rect2(5, 10);
rect2.display();

// Creating an object using copy constructor


Rectangle rect3 = rect2;
rect3.display();

return 0;
}
2. Demonstrate a C++ program using constructor overloading.
#include <iostream>

class Complex {
private:
double real;
double imag;

public:
// Default constructor
Complex() : real(0.0), imag(0.0) {}

// Parameterized constructor
Complex(double r, double i) : real(r), imag(i) {}

// Constructor overloading
Complex(double r) : real(r), imag(0.0) {}

void display() const {


std::cout << "Real: " << real << ", Imaginary: " << imag << std::endl;
}
};

int main() {
// Creating an object using default constructor
Complex c1;
c1.display();

// Creating an object using parameterized constructor


Complex c2(5.5, 3.3);
c2.display();

// Creating an object using constructor overloading


Complex c3(7.7);
c3.display();

return 0;
}
3.Demonstrate a C++ program using binary operator overloading.
#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
// Constructor to initialize the object’s value
Complex(double r = 0, double i = 0) {
real = r;
imag = i;
}

// Overloading (+) operator to perform complex number addition


Complex operator+(const Complex& c) {
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};

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

Complex sum = c1 + c2;

cout << "Complex Number 1: ";


c1.display();
cout << "Complex Number 2: ";
c2.display();
cout << "Sum: ";
sum.display();

return 0;
}
4.Demonstrate a C++ program using unary operator overloading.
#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
// Constructor to initialize the object’s value
Complex(double r = 0, double i = 0) {
real = r;
imag = i;
}

// Overloading - (unary minus) operator


Complex operator-() {
Complex temp;
temp.real = -real;
temp.imag = -imag;
return temp;
}

void display() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(3, 4);

cout << "Complex Number 1: ";


c1.display();
Complex negC1 = -c1; // Unary minus operation

cout << "Unary Minus of Complex Number 1: ";


negC1.display();

return 0;
}
5.Write a C++ program to demonstrate strcpy(),strcat() and strlen() function.
#include <iostream>
#include <cstring>

using namespace std;

int main() {
char str1[50] = "reva, ";
char str2[50] = "presidency!";
char str3[50];

cout << "Original strings:" << endl;


cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;

// Demonstrate strcpy()
strcpy(str3, str1);
cout << "\nstrcpy(str3, str1): " << endl;
cout << "str3: " << str3 << endl;

// Demonstrate strcat()
strcat(str1, str2);
cout << "\nstrcat(str1, str2): " << endl;
cout << "str1: " << str1 << endl;

// Demonstrate strlen()
int len1 = strlen(str1);
int len2 = strlen(str2);
cout << "\nstrlen() function:" << endl;
cout << "Length of str1: " << len1 << endl;
cout << "Length of str2: " << len2 << endl;

return 0;
}
6. Write a C++ program to demonstrate strcmp() function
#include <iostream>
#include <cstring>

using namespace std;

int main() {
char str1[50] = "Hello";
char str2[50] = "Hello";
char str3[50] = "hello";
char str4[50] = "Goodbye";

cout << "Comparing strings using strcmp():" << endl;


int result1 = strcmp(str1, str2);
cout << "strcmp(str1, str2): " << result1 << endl;
if (result1 == 0) {
cout << "str1 and str2 are equal." << endl;
} else {
cout << "str1 and str2 are not equal." << endl;
}

int result2 = strcmp(str1, str3);


cout << "strcmp(str1, str3): " << result2 << endl;
if (result2 == 0) {
cout << "str1 and str3 are equal." << endl;
} else {
cout << "str1 and str3 are not equal." << endl;
}

int result3 = strcmp(str1, str4);


cout << "strcmp(str1, str4): " << result3 << endl;
if (result3 == 0) {
cout << "str1 and str4 are equal." << endl;
} else {
cout << "str1 and str4 are not equal." << endl;
}

return 0;
}
MODULE 4:
1. Write a C++ program to resolve inheritance ambiguity.
#include <iostream>
using namespace std;

// Base class
class A {
public:
virtual void foo() {
cout << "A::foo()" << endl;
}
};

// Base class
class B {
public:
void foo() {
cout << "B::foo()" << endl;
}
};

// Derived class
class C : public A, public B {
public:
//void foo() {
// cout << "C::foo()" << endl;
//}
};
int main() {
C obj;
//obj.foo(); // This would be ambiguous, as C inherits foo() from both A and B
A* ptr = &obj;
ptr->foo(); // Output: A::foo()
B* ptr2 = &obj;
ptr2->foo(); // Output: B::foo()
return 0;
}
2. Write a C++ program to calculate area of rectangle using single inheritance.
#include <iostream>
using namespace std;

class Shape {
protected:
int width;
int height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
};

class Rectangle : public Shape {


public:
int getArea() {
return (width * height);
}
};

int main() {
Rectangle rect;

rect.setDimensions(5, 7);

cout << "Total area: " << rect.getArea() << endl;

return 0;
}
3.Write a C++ program to calculate perimeter of rectangle using single inheritance.
#include <iostream>
using namespace std;

class Shape {
protected:
int width;
int height;
public:
void setDimensions(int w, int h) {
width = w;
height = h;
}
};
class Rectangle : public Shape {
public:
int getPerimeter() {
return 2 * (width + height);
}
};

int main() {
Rectangle rect;

rect.setDimensions(5, 7);

cout << "Total perimeter: " << rect.getPerimeter() << endl;

return 0;
}
4. Write a C++ program to demonstrate virtual function.
#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() {
cout << "Drawing a generic shape." << endl;
}
};

class Circle : public Shape {


public:
void draw() {
cout << "Drawing a circle." << endl;
}
};

class Square : public Shape {


public:
void draw() {
cout << "Drawing a square." << endl;
}
};

int main() {
Shape* shapes[2];
Circle circle;
Square square;

shapes[0] = &circle;
shapes[1] = &square;

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


shapes[i]->draw();
}

return 0;
}
5. Write a C++ program to demonstrate pure virtual function.
#include <iostream>
using namespace std;

class Shape {
public:
virtual void draw() = 0; // Pure virtual function
virtual void area() = 0; // Pure virtual function
};

class Circle : public Shape {


private:
double radius;
public:
Circle(double r) : radius(r) {}

void draw() {
cout << "Drawing a circle." << endl;
}

void area() {
cout << "Area of the circle: " << 3.14 * radius * radius << endl;
}
};

class Square : public Shape {


private:
double side;
public:
Square(double s) : side(s) {}

void draw() {
cout << "Drawing a square." << endl;
}

void area() {
cout << "Area of the square: " << side * side << endl;
}
};

int main() {
Shape* shapes[2];
Circle circle(5.0);
Square square(4.0);

shapes[0] = &circle;
shapes[1] = &square;

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


shapes[i]->draw();
shapes[i]->area();
cout << endl;
}
return 0;
}
MODULE 5:
1. Write a C++ program to demonstrate the use of showpos , noshowpos and endl manipu#include
<iostream>
#include <iomanip>

using namespace std;

int main() {
int a = 10;
int b = -10;

cout << "Using showpos:" << endl;


cout << "a = " << showpos << a << endl;
cout << "b = " << showpos << b << endl;

cout << endl << "Using noshowpos:" << endl;


cout << "a = " << noshowpos << a << endl;
cout << "b = " << noshowpos << b << endl;

cout << endl << "Using endl:" << endl;


cout << "Hello, World!" << endl;
cout << "This is a test." << endl;

return 0;
}
2.Write a C++ program to demonstrate the use of dec,oct and Hexa manipulators.
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
int decimal = 10;
int octal = 12;
int hexadecimal = 0xA;

cout << "Using dec:" << endl;


cout << "decimal = " << dec << decimal << endl;
cout << "octal = " << dec << octal << endl;
cout << "hexadecimal = " << dec << hexadecimal << endl;

cout << endl << "Using oct:" << endl;


cout << "decimal = " << oct << decimal << endl;
cout << "octal = " << oct << octal << endl;
cout << "hexadecimal = " << oct << hexadecimal << endl;

cout << endl << "Using hex:" << endl;


cout << "decimal = " << hex << decimal << endl;
cout << "octal = " << hex << octal << endl;
cout << "hexadecimal = " << hex << hexadecimal << endl;

return 0;
}
3. Write a C++ program to demonstrate the use of uppercase, nouppercase and setfill
manipulators.
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
double num = 123.456;
int width = 15;

cout << "Using uppercase:" << endl;


cout << setw(width) << setprecision(3) << uppercase << num << endl;

cout << endl << "Using nouppercase:" << endl;


cout << setw(width) << setprecision(3) << nouppercase << num << endl;

cout << endl << "Using setfill:" << endl;


cout << setw(width) << setfill(’*’) << setprecision(3) << nouppercase << num << endl;

return 0;
}
4.Write a C++ program to demonstrate the use of noshowpoint, showpoint, left and right
manipulators
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
double num = 123.456;
int width = 15;

cout << "Using showpoint:" << endl;


cout << setw(width) << setprecision(3) << showpoint << num << endl;

cout << endl << "Using noshowpoint:" << endl;


cout << setw(width) << setprecision(3) << noshowpoint << num << endl;

cout << endl << "Using left:" << endl;


cout << setw(width) << left << num << endl;

cout << endl << "Using right:" << endl;


cout << setw(width) << right << num << endl;

return 0;
}
5. Write a C ++ program to add two numbers using function templates.
#include <iostream>

using namespace std;

template <typename T>


T add(T a, T b) {
return a + b;
}

int main() {
int num1 = 10, num2 = 20;
double num3 = 3.5, num4 = 6.7;

cout << "Sum of " << num1 << " and " << num2 << " is: " << add(num1, num2) << endl;
cout << "Sum of " << num3 << " and " << num4 << " is: " << add(num3, num4) << endl;

return 0;
}
6. Write a C ++ program to add two numbers using class templates.
#include <iostream>
using namespace std;

template <typename T>


class AddTwoNumbers {
T num1, num2;

public:
AddTwoNumbers(T a, T b) {
num1 = a;
num2 = b;
}

T add() {
return num1 + num2;
}
};

int main() {
AddTwoNumbers<int> addNumbers(3, 4); // passing int values
cout << "Sum: " << addNumbers.add() << endl;

AddTwoNumbers<float> addNumbersFloat(3.5, 4.7); // passing float values


cout << "Sum: " << addNumbersFloat.add() << endl;

return 0;
}
7.Write a C++ program for Simple Calculator Using Class Templates.
#include <iostream>
using namespace std;

template <typename T>


class SimpleCalculator {
T num1, num2;

public:
SimpleCalculator(T a, T b) {
num1 = a;
num2 = b;
}

T add() {
return num1 + num2;
}

T subtract() {
return num1 - num2;
}

T multiply() {
return num1 * num2;
}

T divide() {
if (num2 == 0) {
cout << "Error! Division by zero is not allowed." << endl;
return 0;
}
return num1 / num2;
}
};

int main() {
SimpleCalculator<int> calc(10, 5); // passing int values
cout << "Addition: " << calc.add() << endl;
cout << "Subtraction: " << calc.subtract() << endl;
cout << "Multiplication: " << calc.multiply() << endl;
cout << "Division: " << calc.divide() << endl;

SimpleCalculator<float> calcFloat(3.5, 4.7); // passing float values


cout << "Addition: " << calcFloat.add() << endl;
cout << "Subtraction: " << calcFloat.subtract() << endl;
cout << "Multiplication: " << calcFloat.multiply() << endl;
cout << "Division: " << calcFloat.divide() << endl;

return 0;
}
8.Write a C++ program to swap the integer values, float values and character using function
template.
#include <iostream>
using namespace std;

template <typename T>


void swapValues(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}

int main() {
int x = 10, y = 20;
cout << "Before swapping integers: x = " << x << ", y = " << y << endl;
swapValues(x, y);
cout << "After swapping integers: x = " << x << ", y = " << y << endl;

float a = 3.5, b = 4.7;


cout << "Before swapping floats: a = " << a << ", b = " << b << endl;
swapValues(a, b);
cout << "After swapping floats: a = " << a << ", b = " << b << endl;

char c = ’A’, d = ’B’;


cout << "Before swapping characters: c = " << c << ", d = " << d << endl;
swapValues(c, d);
cout << "After swapping characters: c = " << c << ", d = " << d << endl;

return 0;
}
9. Write a C++ program to find maximum of two data items using function template.
#include <iostream>
using namespace std;

template <typename T>


T findMax(T a, T b) {
return (a > b) ? a : b;
}

int main() {
int x = 10, y = 20;
cout << "Maximum of " << x << " and " << y << " is " << findMax(x, y) << endl;

float a = 3.5, b = 4.7;


cout << "Maximum of " << a << " and " << b << " is " << findMax(a, b) << endl;

char c = ’A’, d = ’B’;


cout << "Maximum of " << c << " and " << d << " is " << findMax(c, d) << endl;

return 0;
}
part B
module 1:
1.Create a C++ program to find out area of circle, square and trapezium using concept of
function overloading
#include <iostream>
using namespace std;

double area(double r) {
return 3.14 * r * r;
}

int area(int s) {
return s * s;
}

double area(double b1, double b2, double h) {


return 0.5 * (b1 + b2) * h;
}

int main() {
double r, b1, b2, h, s;
cout << "Enter radius of circle: ";
cin >> r;
cout << "Area of circle is: " << area(r) << endl;
cout << "Enter side of square: ";
cin >> s;
cout << "Area of square is: " << area(s) << endl;

cout << "Enter base1, base2, and height of trapezium: ";


cin >> b1 >> b2 >> h;
cout << "Area of trapezium is: " << area(b1, b2, h) << endl;

return 0;
}
2. Create a C++ program to display sum and average of array elements using for loop.

#include <iostream>

int main() {
int arr[5]; // declare an array of 5 integers
int sum = 0; // initialize sum to 0

// input array elements


std::cout << "Enter 5 integers: ";
for (int i = 0; i < 5; i++) {
std::cin >> arr[i];
}

// calculate sum and average using for loop


for (int i = 0; i < 5; i++) {
sum += arr[i]; // add each element to the sum
}

double average = static_cast<double>(sum) / 5; // calculate average

// display results
std::cout << "Sum: " << sum << std::endl;
std::cout << "Average: " << average << std::endl;

return 0;
}
3. Create a C++ program to check number entered by user is Prime or Not
#include <iostream>
using namespace std;

int main() {
int num;
int flag = 0;

cout << "Enter a number: ";


cin >> num;

if (num <= 1) {
cout << num << " is not a prime number." << endl;
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
flag = 1;
break;
}
}

if (flag == 0) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
}

return 0;
}
4. Create a C++ program to display Fibonacci Series using Function.
#include <iostream>
using namespace std;

int main() {
int num;
int flag = 0;

cout << "Enter a number: ";


cin >> num;

if (num <= 1) {
cout << num << " is not a prime number." << endl;
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
flag = 1;
break;
}
}

if (flag == 0) {
cout << num << " is a prime number." << endl;
} else {
cout << num << " is not a prime number." << endl;
}
}

return 0;
}
5.Create a C++ program to interchange the two values using call by reference.
#include <iostream>
using namespace std;

void swap(int* a, int* b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 5, y = 10;
cout << "Before swapping: x = " << x << ", y = " << y << endl;
swap(&x, &y);
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}
6.Create a C++ program to multiply the two matrices
#include <iostream>
using namespace std;

const int MAX_SIZE = 10;

void inputMatrix(int matrix[][MAX_SIZE], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> matrix[i][j];
}
}
}

void multiplyMatrices(int A[][MAX_SIZE], int B[][MAX_SIZE], int C[][MAX_SIZE], int m, int n, int p, int q) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < q; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}

void outputMatrix(int matrix[][MAX_SIZE], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}

int main() {
int A[MAX_SIZE][MAX_SIZE], B[MAX_SIZE][MAX_SIZE], C[MAX_SIZE][MAX_SIZE];
int m, n, p, q;

cout << "Enter the number of rows and columns for matrix A: ";
cin >> m >> n;
cout << "Enter the elements of matrix A:" << endl;
inputMatrix(A, m, n);

cout << "Enter the number of rows and columns for matrix B: ";
cin >> p >> q;
if (n != p) {
cout << "Error: The number of columns in matrix A must be equal to the number of rows in matrix B."
<< endl;
return 1;
}
cout << "Enter the elements of matrix B:" << endl;
inputMatrix(B, p, q);

multiplyMatrices(A, B, C, m, n, p, q);

cout << "The product of matrices A and B is:" << endl;


outputMatrix(C, m, q);

return 0;
}
module 2:
1.Create a C++ program to calculate area and volume of a room using class and object concept
where length, breadth and height should be entered by user at run time.
#include <iostream>
using namespace std;

class Room {
private:
int length;
int breadth;
int height;

public:
// Constructor to initialize the dimensions of the room
Room(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}

// Function to calculate the area of the room


int calculateArea() {
return length * breadth;
}

// Function to calculate the volume of the room


int calculateVolume() {
return length * breadth * height;
}
};

int main() {
int l, b, h;

// Input the dimensions of the room


cout << "Enter the length of the room: ";
cin >> l;
cout << "Enter the breadth of the room: ";
cin >> b;
cout << "Enter the height of the room: ";
cin >> h;

// Create an object of the Room class with the input dimensions


Room room(l, b, h);

// Calculate and display the area and volume of the room


cout << "The area of the room is: " << room.calculateArea() << endl;
cout << "The volume of the room is: " << room.calculateVolume() << endl;

return 0;
}
2. Create a C++ program to read Student Information like name, regno and three subjects marks
from the user also calculate and print sum and average of the marks along with above
information. (make data members - private). Apply class and object concept
#include <iostream>
#include <string>
using namespace std;

class Student {
private:
string name;
int regno;
int sub1, sub2, sub3;

public:
// Function to input student information
void inputStudentInfo() {
cout << "Enter the name of the student: ";
cin.ignore();
getline(cin, name);
cout << "Enter the registration number of the student: ";
cin >> regno;
cout << "Enter the marks of the student in three subjects: ";
cin >> sub1 >> sub2 >> sub3;
}

// Function to display student information


void displayStudentInfo() {
cout << "Name: " << name << endl;
cout << "Registration Number: " << regno << endl;
cout << "Marks in Subject 1: " << sub1 << endl;
cout << "Marks in Subject 2: " << sub2 << endl;
cout << "Marks in Subject 3: " << sub3 << endl;
}

// Function to calculate the sum of the marks


int calculateSum() {
return sub1 + sub2 + sub3;
}

// Function to calculate the average of the marks


float calculateAverage() {
return (float)(sub1 + sub2 + sub3) / 3;
}
};

int main() {
Student s;

// Input student information


s.inputStudentInfo();
// Display student information
s.displayStudentInfo();

// Calculate and display the sum and average of the marks


cout << "Sum of the marks: " << s.calculateSum() << endl;
cout << "Average of the marks: " << s.calculateAverage() << endl;

return 0;
}
3.Create a C++ program to input of name and marks of 5 students by creating an array of the
objects of students
#include <iostream>
#include <string>
using namespace std;

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

public:
// Function to input student information
void inputStudentInfo() {
cout << "Enter the name of the student: ";
cin.ignore();
getline(cin, name);
cout << "Enter the marks of the student in three subjects: ";
cin >> marks[0] >> marks[1] >> marks[2];
}

// Function to display student information


void displayStudentInfo() {
cout << "Name: " << name << endl;
cout << "Marks in Subject 1: " << marks[0] << endl;
cout << "Marks in Subject 2: " << marks[1] << endl;
cout << "Marks in Subject 3: " << marks[2] << endl;
}

// Function to calculate the average of the marks


float calculateAverage() {
return (float)(marks[0] + marks[1] + marks[2]) / 3;
}
};

int main() {
Student students[5];

// Input student information for all 5 students


for (int i = 0; i < 5; i++) {
cout << "Enter information for student " << i+1 << ":" << endl;
students[i].inputStudentInfo();
}

// Display student information for all 5 students


for (int i = 0; i < 5; i++) {
cout << "Information for student " << i+1 << ":" << endl;
students[i].displayStudentInfo();
cout << "Average of the marks: " << students[i].calculateAverage() << endl;
cout << endl;
}

return 0;
}
module 3:
1.Create a C++ program to convert a decimal number into binary number using the constructor
and destructor.

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

class DecimalToBinary {
private:
int decimal;
string binary;

public:
// Constructor to convert decimal to binary
DecimalToBinary(int decimal) {
this->decimal = decimal;
this->binary = bitset<32>(decimal).to_string();
}

// Destructor to print the binary representation


~DecimalToBinary() {
cout << "The binary representation of " << decimal << " is: " << binary << endl;
}
};

int main() {
int decimal;

cout << "Enter a decimal number: ";


cin >> decimal;

// Create an object of the DecimalToBinary class to convert the decimal number to binary
DecimalToBinary dtb(decimal);

return 0;
}
2.Create a C++ program to display the reverse of a number using the constructor.
#include <iostream>

class ReverseNumber {
int num;

public:
ReverseNumber(int n) {
num = n;
}

void displayReverse() {
int reversedNum = 0;
while (num != 0) {
reversedNum = reversedNum * 10 + (num % 10);
num /= 10;
}
std::cout << "Reversed number: " << reversedNum << std::endl;
}
};

int main() {
int num;
std::cout << "Enter a number: ";
std::cin >> num;
ReverseNumber rn(num);
rn.displayReverse();
return 0;
}
3.Create a C++ program to display the reverse of a number using the constructor overloading.
#include <iostream>

class ReverseNumber {
int num;
int reversedNum;

public:
// Default constructor
ReverseNumber() {
num = 0;
reversedNum = 0;
}

// Parameterized constructor
ReverseNumber(int n) {
num = n;
reversedNum = 0;
while (n != 0) {
reversedNum = reversedNum * 10 + (n % 10);
n /= 10;
}
}

// Copy constructor
ReverseNumber(const ReverseNumber& rn) {
num = rn.num;
reversedNum = rn.reversedNum;
}

// Assignment operator
ReverseNumber& operator=(const ReverseNumber& rn) {
if (this != &rn) {
num = rn.num;
reversedNum = rn.reversedNum;
}
return *this;
}

void displayReverse() {
std::cout << "Original number: " << num << std::endl;
std::cout << "Reversed number: " << reversedNum << std::endl;
}
};

int main() {
ReverseNumber rn1; // Default constructor
rn1.displayReverse();

int num;
std::cout << "Enter a number: ";
std::cin >> num;
ReverseNumber rn2(num); // Parameterized constructor
rn2.displayReverse();

ReverseNumber rn3(rn2); // Copy constructor


rn3.displayReverse();

ReverseNumber rn4; // Default constructor


rn4 = rn2; // Assignment operator
rn4.displayReverse();

return 0;
}
4.Create a C++ program to add two complex numbers using Binary Operator Overloading.
#include <iostream>

class Complex {
double real;
double imag;

public:
// Default constructor
Complex() {
real = 0.0;
imag = 0.0;
}

// Parameterized constructor
Complex(double r, double i) {
real = r;
imag = i;
}

// Overloading binary operator ’+’ for complex numbers


Complex operator+(const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}

// Overloading binary operator ’+’ for real numbers


Complex operator+(double r) {
return Complex(real + r, imag);
}

void display() {
std::cout << real << " + " << imag << "i" << std::endl;
}
};

int main() {
Complex c1(3.5, 2.2);
Complex c2(1.7, 4.9);

Complex c3 = c1 + c2;
c3.display();

Complex c4 = c1 + 2.5;
c4.display();

return 0;
}
5.Create a C++ program to add two matrix using Binary Operator Overloading.

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

class Matrix {
private:
int rows, cols;
int** data;

public:
Matrix(int r, int c) : rows(r), cols(c) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}

~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}

void input() {
cout << "Enter the elements of the matrix:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> data[i][j];
}
}
}
void display() const {
cout << "The matrix is:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << data[i][j] << " ";
}
cout << endl;
}
}

Matrix operator+(const Matrix& m) const {


if (rows != m.rows || cols != m.cols) {
throw invalid_argument("Matrices have different dimensions");
}

Matrix result(rows, cols);


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result.data[i][j] = data[i][j] + m.data[i][j];
}
}
return result;
}
};

int main() {
int r1, c1, r2, c2;

cout << "Enter the dimensions of the first matrix:" << endl;
cin >> r1 >> c1;
Matrix m1(r1, c1);
m1.input();

cout << "Enter the dimensions of the second matrix:" << endl;
cin >> r2 >> c2;
Matrix m2(r2, c2);
m2.input();

try {
if (r1 != r2 || c1 != c2) {
cout << "Error: Matrices have different dimensions" << endl;
return 1;
}

Matrix m3 = m1 + m2;
cout << "The sum of the matrices is:" << endl;
m3.display();
} catch (const invalid_argument& e) {
cerr << "Error: " << e.what() << endl;
return 1;
}

return 0;
}
6. Create a C++ program to add two complex numbers using Friend function.
#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

void input() {
cout << "Enter the real and imaginary parts of the complex number: ";
cin >> real >> imag;
}

void display() const {


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

friend Complex operator+(const Complex& c1, const Complex& c2);


};

Complex operator+(const Complex& c1, const Complex& c2) {


Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}

int main() {
Complex c1, c2, c3;

c1.input();
c2.input();

c3 = c1 + c2;

cout << "The complex numbers are: ";


c1.display();
c2.display();

cout << "Their sum is: ";


c3.display();

return 0;
}
module 4:Multilevel Inheritance:
1.Write a C++ program to calculate the percentage of a student. Accept the marks of three
subjects in base class. A class will derived from the above mentioned class which includes a
function to find the total marks obtained and another class derived from this class which
calculates and displays the percentage of student.
#include <iostream>
using namespace std;

class Student {
protected:
int sub1, sub2, sub3;

public:
Student() : sub1(0), sub2(0), sub3(0) {}

void input() {
cout << "Enter the marks obtained in three subjects: ";
cin >> sub1 >> sub2 >> sub3;
}
};

class TotalMarks : public Student {


public:
int getTotal() {
return sub1 + sub2 + sub3;
}
};

class Percentage : public TotalMarks {


public:
void displayPercentage() {
double percentage = (getTotal() * 100.0) / 300.0;
cout << "The percentage of the student is: " << percentage << "%" << endl;
}
};

int main() {
Percentage p;

p.input();
p.displayPercentage();

return 0;
}
2.In a bank, different customers have savings account. Some customers may have taken a loan
from the bank. So, bank always maintains information about bank depositors and borrowers.
Design a Base class Customer (name, phone-number).
Derive a class Depositor (accno, balance) from Customer.
Again, derive a class Borrower (loan-no, loan-amt) from Depositor.
Write necessary member functions to read and display the details of customers
#include <iostream>
using namespace std;

class Customer {
protected:
string name;
string phoneNumber;

public:
Customer() : name(""), phoneNumber("") {}

void input() {
cout << "Enter the name of the customer: ";
cin.ignore();
getline(cin, name);

cout << "Enter the phone number of the customer: ";


cin >> phoneNumber;
}

void display() const {


cout << "Name: " << name << endl;
cout << "Phone Number: " << phoneNumber << endl;
}
};

class Depositor : public Customer {


private:
int accNo;
double balance;

public:
Depositor() : accNo(0), balance(0.0) {}

void input() {
Customer::input();

cout << "Enter the account number of the depositor: ";


cin >> accNo;

cout << "Enter the balance in the account: ";


cin >> balance;
}

void display() const {


Customer::display();

cout << "Account Number: " << accNo << endl;


cout << "Balance: " << balance << endl;
}
};

class Borrower : public Depositor {


private:
int loanNo;
double loanAmt;

public:
Borrower() : loanNo(0), loanAmt(0.0) {}

void input() {
Depositor::input();

cout << "Enter the loan number of the borrower: ";


cin >> loanNo;

cout << "Enter the loan amount: ";


cin >> loanAmt;
}

void display() const {


Depositor::display();

cout << "Loan Number: " << loanNo << endl;


cout << "Loan Amount: " << loanAmt << endl;
}
};

int main() {
Borrower b;

b.input();
b.display();

return 0;
}
3.Write a C++ program to design a base class Person (name, address, phone_no). Derive a class
Employee (eno, ename) from Person. Derive a class Manager (designation, department name,
basic-salary) from Employee. Write a menu driven program to:

a. Accept all details of ’n’ managers.


b. Display manager having highest salary
#include<iostream>
using namespace std;
class Person //Base Class
{
protected:
char pname[50], address[100];
int phone_no;
};
//Class Employee - Derived Class. Derived from Class Person and Base Class of Manager
class Employee : public Person
{
public:
int eno;
char ename[50];
};
class Manager : public Employee //Class Manager - Derived Class. Derived from Class Employee
{
public:
char designation[50], deptname[100];
float basic_salary;
public:
void accept_details()
{
cout<<"\n Enter Details of Manager ";
cout<<"\n -------------------------- ";
cout<<"\n Enter Employee No. : ";
cin>>eno;
cout<<"\n Enter Name : ";
cin>>ename;
cout<<"\n Enter Address : ";
cin>>address;
cout<<"\n Enter Phone No. : ";
cin>>phone_no;
cout<<"\n Enter Designation : ";
cin>>designation;
cout<<"\n Enter Department Name : ";
cin>>deptname;
cout<<"\n Enter Basic Salary : ";
cin>>basic_salary;
}
};
int main()
{
int i,cnt,temp;
Manager man[100];
cout<<"\n How Many Managers You Want to Enter? : ";
cin>>cnt; //Accept details for ’n’ managers
for(i=1;i<=cnt;i++)
{
man[i].accept_details();
}
temp=0;
for(i=1;i<=cnt;i++)
{
if(man[temp].basic_salary<man[i].basic_salary)
temp=i;
}
cout<<"\n Manager with Highest Salary is : "<<man[temp].basic_salary;
cout<<" \n And, Manager Name is : "<<man[temp].ename;
return 0;
}
4.4. Write a C++ program to implement the following class hierarchy:
Student: id, name
StudentExam (derived from Student): Marks of 6 subjects
StudentResult (derived from StudentExam) : percentage
Define appropriate functions to accept and display details.
Create ’n’ objects of the StudentResult class and display the marklist.
#include<iostream>
#include<stdio.h>
using namespace std;

class Student
{
int roll;
char name[25];
public:
void getdata()
{
cout<<"\n -----------------------------------------";
cout<<"\n Enter Roll No. : ";
cin>>roll;
cout<<"\n Enter Student Name : ";
cin>>name;
}
void putdata()
{
cout<<"\n -----------------------------------------";
cout<<"\n ********** Student Marklist **********";
cout<<"\n -----------------------------------------";
cout<<"\n Roll No. : "<<roll;
cout<<"\n Student Name : "<<name<<endl;
}
};
class StudentExam : public Student //Class StudentExam derived from Class Student
{
public:
int sub1, sub2, sub3, sub4, sub5, sub6;
float per;
public:
void accept_data()
{
getdata();
cout<<"\n Enter Marks for Subject 1 : ";
cin>>sub1;
cout<<"\n Enter Marks for Subject 2 : ";
cin>>sub2;
cout<<"\n Enter Marks for Subject 3 : ";
cin>>sub3;
cout<<"\n Enter Marks for Subject 4 : ";
cin>>sub4;
cout<<"\n Enter Marks for Subject 5 : ";
cin>>sub5;
cout<<"\n Enter Marks for Subject 6 : ";
cin>>sub6;
}
void display_data()
{
putdata();
cout<<"\n Marks of Subject 1 : "<<sub1;
cout<<"\n Marks of Subject 2 : "<<sub2;
cout<<"\n Marks of Subject 3 : "<<sub3;
cout<<"\n Marks of Subject 4 : "<<sub4;
cout<<"\n Marks of Subject 5 : "<<sub5;
cout<<"\n Marks of Subject 6 : "<<sub6;
}
};
class StudentResult : public StudentExam //Class StudentResult derived from Class StudentExam
{
public:
void calculate ()
{
per = (sub1+sub2+sub3+sub4+sub5+sub6)/6.0;
cout<<"\n\n Total Percentage : "<<per;
cout<<"\n ----------------------------------------- \n";
}
};
int main()
{
StudentResult str; //Object ’str’ is created of derived Class StudentResult
int cnt, i;
cout<<"\n Enter No. of Students You Want? : ";
cin>>cnt;
for(i=0; i<cnt; i++)
{
str.accept_data();
str.display_data();
str.calculate();
}
return 0;
}
5. Create a C++ program to calculate area of rectangle using multilevel inheritance.
#include <iostream>

using namespace std;

// Base class Shape


class Shape {
public:
virtual float area() = 0; // Pure virtual function
};

// Intermediate class RectangleShape


class RectangleShape : public Shape {
protected:
float length, breadth;

public:
RectangleShape(float l, float b) : length(l), breadth(b) {}

float area() {
return length * breadth;
}
};

// Derived class Rectangle


class Rectangle : public RectangleShape {
public:
Rectangle(float l, float b) : RectangleShape(l, b) {}

void displayArea() {
cout << "Area of rectangle: " << area() << endl;
}
};

int main() {
Rectangle rect(5.0, 10.0);
rect.displayArea();

return 0;
}
6.Create a C++ program to calculate perimeter of rectangle using multilevel inheritance
#include <iostream>

using namespace std;

// Base class Shape


class Shape {
public:
virtual float perimeter() = 0; // Pure virtual function
};

// Intermediate class RectangleShape


class RectangleShape : public Shape {
protected:
float length, breadth;

public:
RectangleShape(float l, float b) : length(l), breadth(b) {}

float perimeter() {
return 2 * (length + breadth);
}
};

// Derived class Rectangle


class Rectangle : public RectangleShape {
public:
Rectangle(float l, float b) : RectangleShape(l, b) {}

void displayPerimeter() {
cout << "Perimeter of rectangle: " << perimeter() << endl;
}
};

int main() {
Rectangle rect(5.0, 10.0);
rect.displayPerimeter();

return 0;
}
7.Create a C++ program to calculate area of circle using multilevel inheritance.
#include <iostream>
#include <cmath>

using namespace std;

// Base class Shape


class Shape {
public:
virtual float area() = 0; // Pure virtual function
};

// Intermediate class CircleShape


class CircleShape : public Shape {
protected:
float radius;

public:
CircleShape(float r) : radius(r) {}

float area() {
return M_PI * radius * radius;
}
};

// Derived class Circle


class Circle : public CircleShape {
public:
Circle(float r) : CircleShape(r) {}

void displayArea() {
cout << "Area of circle: " << area() << endl;
}
};

int main() {
Circle circle(5.0);
circle.displayArea();

return 0;
}
8.Create a C++ program to calculate perimeter of circle using multilevel inheritance.
#include <iostream>
#include <cmath>

using namespace std;

// Base class Shape


class Shape {
public:
virtual float circumference() = 0; // Pure virtual function
};

// Intermediate class CircleShape


class CircleShape : public Shape {
protected:
float radius;

public:
CircleShape(float r) : radius(r) {}

float circumference() {
return 2 * M_PI * radius;
}
};

// Derived class Circle


class Circle : public CircleShape {
public:
Circle(float r) : CircleShape(r) {}

void displayCircumference() {
cout << "Circumference of circle: " << circumference() << endl;
}
};

int main() {
Circle circle(5.0);
circle.displayCircumference();

return 0;
}
9. Create a C++ program to display student five subjects mark list using multilevel inheritance.
#include <iostream>
#include <string>

using namespace std;

// Base class Person


class Person {
protected:
string name;

public:
Person(string n) : name(n) {}

void displayName() {
cout << "Name: " << name << endl;
}
};

// Intermediate class Student


class Student : public Person {
protected:
int rollNo;

public:
Student(string n, int r) : Person(n), rollNo(r) {}

void displayRollNo() {
cout << "Roll No: " << rollNo << endl;
}
};

// Derived class MarkList


class MarkList : public Student {
private:
int marks[5];

public:
MarkList(string n, int r, int m1, int m2, int m3, int m4, int m5)
: Student(n, r) {
marks[0] = m1;
marks[1] = m2;
marks[2] = m3;
marks[3] = m4;
marks[4] = m5;
}

void displayMarkList() {
displayName();
displayRollNo();
cout << "Mark List:" << endl;
cout << "Subject 1: " << marks[0] << endl;
cout << "Subject 2: " << marks[1] << endl;
cout << "Subject 3: " << marks[2] << endl;
cout << "Subject 4: " << marks[3] << endl;
cout << "Subject 5: " << marks[4] << endl;
}
};

int main() {
MarkList student("John Doe", 123, 80, 70, 90, 85, 95);
student.displayMarkList();

return 0;
}
10. Consider an example of declaring the examination result. Design three classes: Student,
Exam, and Result. The Student class has data members such as those representing roll number
and name. Create the class Exam by inheriting the Student class. The Exam class adds data
members representing the marks scored in sic subjects. Derive the Result from the Exam class
and has its own data members such as total_marks. Write a C++ program to model this
relationship.What type of inheritance this model belongs to?
#include<iostream>
using namespace std;
class STUDENT{
private:
int roll_no;
string name;
public:
STUDENT(){

}
STUDENT(int roll, string n){
roll_no = roll;
name = n;
}
};

class EXAM: public STUDENT{


private:
int * arr;
int number_of_subjects;
public:
EXAM(){
number_of_subjects = 6;
arr = new int[number_of_subjects];
}
int getMarks(){
cout<<"Enter student’s marks for six subject\n";
for(int i=0; i<6; i++){
cout<<"Mark: "<<(i+1)<<endl;
cin>>arr[i];
}
int sum = 0;
for(int i=0; i<6; i++){
sum += arr[i];
}
return sum;
}
};

class RESULT: public EXAM{


private:
int total_marks;
public:
int displayTotalMarks(){
int p = getMarks();

}
};

int main(){
RESULT t;
cout<<"The total marks is \t"<<t.getMarks();
return 0;
}
Multiple Inheritance:
1.Create a base class Patient (pat-name, age, sex) and IPD (ward-no, bed-no, charge-per-day).
Derive a class IPD-patient from these two base classes with no-of-days-admitted attribute
#include <iostream>
#include <string>

class Patient {
protected:
std::string name;
int age;
char sex;

public:
Patient(std::string name, int age, char sex) : name(name), age(age), sex(sex) {}
std::string getName() const { return name; }
int getAge() const { return age; }
char getSex() const { return sex; }
};

class IPD {
protected:
int wardNo;
int bedNo;
double chargePerDay;
public:
IPD(int wardNo, int bedNo, double chargePerDay) : wardNo(wardNo), bedNo(bedNo),
chargePerDay(chargePerDay) {}
int getWardNo() const { return wardNo; }
int getBedNo() const { return bedNo; }
double getChargePerDay() const { return chargePerDay; }
};

class IPDPatient : public Patient, public IPD {


private:
int noOfDaysAdmitted;

public:
IPDPatient(std::string name, int age, char sex, int wardNo, int bedNo, double chargePerDay, int
noOfDaysAdmitted)
: Patient(name, age, sex), IPD(wardNo, bedNo, chargePerDay),
noOfDaysAdmitted(noOfDaysAdmitted) {}
int getNoOfDaysAdmitted() const { return noOfDaysAdmitted; }
double getTotalCharge() const { return noOfDaysAdmitted * getChargePerDay(); }
};

int main() {
IPDPatient patient("sharath", 21, ’M’, 1, 2, 500, 25);
std::cout << "Name: " << patient.getName() << std::endl;
std::cout << "Age: " << patient.getAge() << std::endl;
std::cout << "Sex: " << patient.getSex() << std::endl;
std::cout << "Ward No: " << patient.getWardNo() << std::endl;
std::cout << "Bed No: " << patient.getBedNo() << std::endl;
std::cout << "Charge per Day: $" << patient.getChargePerDay() << std::endl;
std::cout << "No. of Days Admitted: " << patient.getNoOfDaysAdmitted() << std::endl;
std::cout << "Total Charge: $" << patient.getTotalCharge() << std::endl;
return 0;
}
2. Create a C++ program to calculate area and perimeter of rectangle using multiple inheritance.
#include <iostream>

using namespace std;

class Length {
protected:
double len;

public:
Length(double len) : len(len) {}
double getLength() const { return len; }
};

class Breadth : public Length {


public:
Breadth(double len) : Length(len) {}
};

class Area : public Length {


public:
Area(double len) : Length(len) {}
double calculateArea(Breadth b) const { return getLength() * b.getLength(); }
};

class Perimeter : public Length {


public:
Perimeter(double len) : Length(len) {}
double calculatePerimeter(Breadth b) const { return 2 * (getLength() + b.getLength()); }
};

int main() {
Breadth breadth(5.0);
Area area(10.0);
Perimeter perimeter(10.0);

cout << "Area: " << area.calculateArea(breadth) << endl;


cout << "Perimeter: " << perimeter.calculatePerimeter(breadth) << endl;

return 0;
}
3.. Create a C++ program to calculate area and perimeter of circle using multiple inheritance.
Area of Circle, A = πr2 Square units
Circumference/ Perimeter of Circle = 2πr
#include <iostream>
#include <cmath>

using namespace std;

class Radius {
protected:
double rad;

public:
Radius(double rad) : rad(rad) {}
double getRadius() const { return rad; }
};

class Area : public Radius {


public:
Area(double rad) : Radius(rad) {}
double calculateArea() const { return M_PI * pow(getRadius(), 2); }
};

class Circumference : public Radius {


public:
Circumference(double rad) : Radius(rad) {}
double calculateCircumference() const { return 2 * M_PI * getRadius(); }
};

int main() {
Area area(5.0);
Circumference circumference(5.0);

cout << "Area: " << area.calculateArea() << endl;


cout << "Circumference: " << circumference.calculateCircumference() << endl;
return 0;
}
4.Create a C++ program to display student five subjects mark list using multiple inheritance.
#include <iostream>
#include <string>

using namespace std;

class Student {
protected:
string name;
int rollNo;

public:
Student(string name, int rollNo) : name(name), rollNo(rollNo) {}
string getName() const { return name; }
int getRollNo() const { return rollNo; }
};

class Marks : public Student {


protected:
int marks[5];

public:
Marks(string name, int rollNo, int marks[5]) : Student(name, rollNo) {
for (int i = 0; i < 5; i++) {
this->marks[i] = marks[i];
}
}
void displayMarks() const {
cout << "Marks: " << endl;
for (int i = 0; i < 5; i++) {
cout << "Subject " << i + 1 << ": " << marks[i] << endl;
}
}
};

class Result : public Marks {


private:
float total;
float percentage;

public:
Result(string name, int rollNo, int marks[5]) : Marks(name, rollNo, marks) {
calculateTotal();
calculatePercentage();
}
void displayResult() const {
cout << "Name: " << getName() << endl;
cout << "Roll No: " << getRollNo() << endl;
displayMarks();
cout << "Total: " << total << endl;
cout << "Percentage: " << percentage << "%" << endl;
}
private:
void calculateTotal() {
total = 0;
for (int i = 0; i < 5; i++) {
total += marks[i];
}
}
void calculatePercentage() {
percentage = (total / 500.0) * 100.0;
}
};

int main() {
int marks[5] = {75, 85, 90, 80, 95};
Result result("John Doe", 12345, marks);
result.displayResult();

return 0;
}
Hierarchical inheritance:
1.Create a C++ program to calculate area and perimeter of rectangle using Hierarchical
inheritance.
#include <iostream>

using namespace std;

class Shape {
protected:
int width, height;

public:
Shape(int width, int height) : width(width), height(height) {}
virtual void calculateArea() const = 0;
virtual void calculatePerimeter() const = 0;
};

class Rectangle : public Shape {


public:
Rectangle(int width, int height) : Shape(width, height) {}
void calculateArea() const override {
cout << "Area of rectangle: " << width * height << endl;
}
void calculatePerimeter() const override {
cout << "Perimeter of rectangle: " << 2 * (width + height) << endl;
}
};

int main() {
Rectangle rectangle(5, 10);
rectangle.calculateArea();
rectangle.calculatePerimeter();

return 0;
}
2. Create a C++ program to calculate area and perimeter of circle using Hierarchical inheritance.
#include <iostream>
#include <cmath>

using namespace std;

class Shape {
protected:
double radius;

public:
Shape(double radius) : radius(radius) {}
virtual void calculateArea() const = 0;
virtual void calculateCircumference() const = 0;
};

class Circle : public Shape {


public:
Circle(double radius) : Shape(radius) {}
void calculateArea() const override {
cout << "Area of circle: " << M_PI * radius * radius << endl;
}
void calculateCircumference() const override {
cout << "Circumference of circle: " << 2 * M_PI * radius << endl;
}
};

int main() {
Circle circle(5.0);
circle.calculateArea();
circle.calculateCircumference();

return 0;
}
3.Create a C++ program to get square and cube of a number using Hierarchical inheritance.
#include <iostream>
using namespace std;

class Number {
protected:
int num;
public:
void getNumber() {
cout << "Enter an integer number: ";
cin >> num;
}
int returnNumber() {
return num;
}
};

class Square : public Number {


public:
int getSquare() {
int sqr;
sqr = returnNumber() * returnNumber();
return sqr;
}
};

class Cube : public Square {


public:
int getCube() {
int cube;
cube = returnNumber() * returnNumber() * returnNumber();
return cube;
}
};

int main() {
Square objS;
Cube objC;
int sqr, cube;

objS.getNumber();
sqr = objS.getSquare();
cout << "Square of " << objS.returnNumber() << " is: " << sqr << endl;

objC.getNumber();
cube = objC.getCube();
cout << "Cube of " << objC.returnNumber() << " is: " << cube << endl;

return 0;
}
Multipath inheritance:
1.. Create a C++ program to calculate area and perimeter of rectangle using multipath
inheritance
#include <iostream>
using namespace std;

class Area {
public:
float area(float l, float b) {
return l * b;
}
};

class Perimeter {
public:
float peri(float l, float b) {
return 2 * (l + b);
}
};

class Rectangle : public Area, public Perimeter {


private:
float length, breadth;
public:
Rectangle() : length(0.0), breadth(0.0) {}
void get_data() {
cout << "Enter length: ";
cin >> length;
cout << "Enter breadth: ";
cin >> breadth;
}
void display() {
cout << "Area = " << area(length, breadth) << endl;
cout << "Perimeter = " << peri(length, breadth) << endl;
}
};

int main() {
Rectangle r;
r.get_data();
r.display();
return 0;
}
2.Create a C++ program to calculate area and perimeter of circle using multipath inheritance.
#include <iostream>
#include <cmath>
using namespace std;

class Area {
public:
float area(float r) {
return 3.14159 * r * r;
}
};

class Perimeter {
public:
float peri(float r) {
return 2 * 3.14159 * r;
}
};

class Circle : public Area, public Perimeter {


private:
float radius;
public:
Circle() : radius(0.0) {}
void get_data() {
cout << "Enter radius: ";
cin >> radius;
}
void display() {
cout << "Area = " << area(radius) << endl;
cout << "Perimeter = " << peri(radius) << endl;
}
};

int main() {
Circle c;
c.get_data();
c.display();
return 0;
}

LAB RECORD QUESTION;


1. Write a C++ program to demonstrate the input and output operations.
#include <iostream>
using namespace std;

int main() {
int num1, num2;
float num3;
char str[100];

// Input Operations
cout << "Enter an integer: ";
cin >> num1;

cout << "Enter another integer: ";


cin >> num2;

cout << "Enter a floating point number: ";


cin >> num3;

cout << "Enter a string: ";


cin.ignore();
cin.getline(str, 100);

// Output Operations
cout << "\nYou entered: " << endl;
cout << "Integer 1: " << num1 << endl;
cout << "Integer 2: " << num2 << endl;
cout << "Floating point number: " << num3 << endl;
cout << "String: " << str << endl;

return 0;
}
2. Write a C++ program to demonstrate the use pf arithmetic operations using simple calculator.
#include <iostream>
using namespace std;

int main() {
int num1, num2;
char operation;

cout << "Enter an integer: ";


cin >> num1;
cout << "Enter an operator (+, -, *, /): ";
cin >> operation;

cout << "Enter another integer: ";


cin >> num2;

switch (operation) {
case '+':
cout << "The result is: " << num1 + num2;
break;
case '-':
cout << "The result is: " << num1 - num2;
break;
case '*':
cout << "The result is: " << num1 * num2;
break;
case '/':
if (num2 == 0) {
cout << "Error: Division by zero is not allowed.";
} else {
cout << "The result is: " << num1 / (float)num2;
}
break;
default:
cout << "Error: Invalid operator.";
break;
}

return 0;
}
3. Write a C++ program to check whether the given number is palindrome or not.
#include <iostream>
using namespace std;

int main() {
int num, reversed_num = 0, remainder, original_num;

cout << "Enter a number: ";


cin >> num;

original_num = num;

// Reverse the number


while (num != 0) {
remainder = num % 10;
reversed_num = reversed_num * 10 + remainder;
num /= 10;
}

// Check if the number is a palindrome


if (original_num == reversed_num) {
cout << original_num << " is a palindrome." << endl;
} else {
cout << original_num << " is not a palindrome." << endl;
}
return 0;
}
4. Write a program to find sum of two complex numbers using Operator Overloading.
#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imag;

public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

Complex operator+(const Complex& other) const {


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

void print() const {


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

friend ostream& operator<<(ostream& os, const Complex& c);


};

ostream& operator<<(ostream& os, const Complex& c) {


os << c.real << " + " << c.imag << "i";
return os;
}

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

c3 = c1 + c2;

cout << "c1 = ";


c1.print();

cout << "c2 = ";


c2.print();

cout << "c3 = c1 + c2 = ";


c3.print();

return 0;
}
5. Demonstrate operator overloading by facilitating the operation of adding two times say T1 and
T2. And display the resultant time as time T3
#include <iostream>
using namespace std;

class Time {
private:
int hours;
int minutes;

public:
Time(int h = 0, int m = 0) : hours(h), minutes(m) {}

Time operator+(const Time& other) const {


int mins = minutes + other.minutes;
int hrs = hours + other.hours + mins / 60;
mins %= 60;
return Time(hrs, mins);
}

void print() const {


cout << hours << " hours " << minutes << " minutes" << endl;
}

friend ostream& operator<<(ostream& os, const Time& t);


};

ostream& operator<<(ostream& os, const Time& t) {


os << t.hours << " hours " << t.minutes << " minutes";
return os;
}

int main() {
Time T1(3, 45);
Time T2(5, 30);
Time T3;

T3 = T1 + T2;

cout << "T1 = ";


T1.print();

cout << "T2 = ";


T2.print();

cout << "T3 = T1 + T2 = ";


T3.print();

return 0;
}
6. Write a program to perform the addition of two matrices using + operator overloading,
subtraction using - operator overloading and product using * operator overloading.
#include <iostream>
using namespace std;

class Matrix {
int a[2][2];

public:
void readmatrix() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> a[i][j];
}
}
}

void displaymatrix() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << a[i][j] << "\t";
}
cout << "\n";
}
}

Matrix operator+(Matrix const &obj) {


Matrix res;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
res.a[i][j] = a[i][j] + obj.a[i][j];
}
}
return res;
}

Matrix operator-(Matrix const &obj) {


Matrix res;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
res.a[i][j] = a[i][j] - obj.a[i][j];
}
}
return res;
}

Matrix operator*(Matrix const &obj) {


Matrix res;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
res.a[i][j] = 0;
for (int k = 0; k < 2; k++) {
res.a[i][j] += a[i][k] * obj.a[k][j];
}
}
}
return res;
}
};

int main() {
Matrix m1, m2, m3;

cout << "Enter elements of first matrix: ";


m1.readmatrix();
cout << "Enter elements of second matrix: ";
m2.readmatrix();

cout << "First matrix: \n";


m1.displaymatrix();

cout << "Second matrix: \n";


m2.displaymatrix();

m3 = m1 + m2;
cout << "Sum of matrices: \n";
m3.displaymatrix();

m3 = m1 - m2;
cout << "Difference of matrices: \n";
m3.displaymatrix();

m3 = m1 * m2;
cout << "Product of matrices: \n";
m3.displaymatrix();

return 0;
}
7. Assume that a bank maintains two kinds of accounts for customers. One called as savings
account and the other a current account. The savings account provides compound interest and
withdrawal facilities but no cheque book facility. The current account provides cheque book
facility but no interest. Current account holders should also maintain a minimum balance and if
the balance falls below this level a service charge is imposed. Create a class account that stores
cust_name, acct_num and type_acct. From this derive the classes cur_acct and sav_acct to
make them more specific to their requirements.
Include functions in order to achieve the following tasks:
a. Accept deposit from a customer and update the balance.
b. displays the balance
c. Compute and deposit interest.
d. Permit withdrawal and update the balance.
e. check for minimum balance, impose penalty, if necessary, and
update the balance.
use member functions to initialize the class members.
#include <iostream>
#include <string>

class Account {
protected:
std::string cust_name;
int acct_num;
double balance;

public:
Account(std::string n, int num, double initial_balance)
: cust_name(n), acct_num(num), balance(initial_balance) {}

virtual void deposit(double amount) {


balance += amount;
}
virtual void withdraw(double amount) {
balance -= amount;
}

virtual void display_balance() const {


std::cout << "Balance: $" << balance << std::endl;
}

std::string get_cust_name() const {


return cust_name;
}

int get_acct_num() const {


return acct_num;
}

double get_balance() const {


return balance;
}
};

class SavingsAccount : public Account {


public:
SavingsAccount(std::string n, int num, double initial_balance)
: Account(n, num, initial_balance) {}

void compute_interest() {
const double rate = 0.05; // 5% annual interest rate
double interest = balance * rate;
deposit(interest);
}
};

class CurrentAccount : public Account {


private:
static constexpr double MIN_BALANCE = 1000.0;
double service_charge;

public:
CurrentAccount(std::string n, int num, double initial_balance, double charge)
: Account(n, num, initial_balance), service_charge(charge) {}

void withdraw(double amount) {


if (balance - amount < MIN_BALANCE) {
amount += service_charge;
std::cout << "Warning: Low balance. A service charge of $"
<< service_charge << " has been added." << std::endl;
}
balance -= amount;
}

void display_balance() const {


std::cout << "Current balance: $" << balance << std::endl;
std::cout << "Minimum balance: $" << MIN_BALANCE << std::endl;
}
};

int main() {
SavingsAccount sa("John Doe", 12345, 5000);
sa.display_balance();
sa.deposit(1000);
sa.display_balance();
sa.compute_interest();
sa.display_balance();

CurrentAccount ca("Jane Doe", 67890, 2000, 50);


ca.display_balance();
ca.deposit(1500);
ca.display_balance();
ca.withdraw(1200);
ca.display_balance();
ca.withdraw(800);
ca.display_balance();

return 0;
}
8.We want to calculate marks of each student of class in Physics, chemistry and mathematics
and the average marks of the class. Create a class named Marks with data members for roll
number, name, and marks. Create three other classes inheriting the marks class, namely physics,
chemistry and maths, which are used to define marks in individual subject of each student. Roll
number of each student will be generated automatically.
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Marks {
protected:
int rollNumber;
string name;
public:
static int rollCounter;
Marks(string n) : name(n) {
rollNumber = ++rollCounter;
}
int getRollNumber() {
return rollNumber;
}
string getName() {
return name;
}
};

int Marks::rollCounter = 0;

class Physics : public Marks {


private:
int physicsMarks;
public:
Physics(string n, int m) : Marks(n) {
physicsMarks = m;
}
int getPhysicsMarks() {
return physicsMarks;
}
};

class Chemistry : public Marks {


private:
int chemistryMarks;
public:
Chemistry(string n, int m) : Marks(n) {
chemistryMarks = m;
}
int getChemistryMarks() {
return chemistryMarks;
}
};

class Maths : public Marks {


private:
int mathsMarks;
public:
Maths(string n, int m) : Marks(n) {
mathsMarks = m;
}
int getMathsMarks() {
return mathsMarks;
}
};

int main() {
vector<Physics> physicsStudents;
vector<Chemistry> chemistryStudents;
vector<Maths> mathsStudents;

int n;
cout << "Enter the number of students: ";
cin >> n;

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


string name;
int marks;
cout << "Enter name and marks of student " << i + 1 << " in Physics: ";
cin >> name >> marks;
physicsStudents.push_back(Physics(name, marks));
cout << "Enter name and marks of student " << i + 1 << " in Chemistry: ";
cin >> name >> marks;
chemistryStudents.push_back(Chemistry(name, marks));
cout << "Enter name and marks of student " << i + 1 << " in Maths: ";
cin >> name >> marks;
mathsStudents.push_back(Maths(name, marks));
}
cout << "\nPhysics Marks:\n";
for(int i = 0; i < n; i++) {
cout << "Roll Number: " << physicsStudents[i].getRollNumber() << ", Name: " <<
physicsStudents[i].getName() << ", Marks: " << physicsStudents[i].getPhysicsMarks() << endl;
}

cout << "\nChemistry Marks:\n";


for(int i = 0; i < n; i++) {
cout << "Roll Number: " << chemistryStudents[i].getRollNumber() << ", Name: " <<
chemistryStudents[i].getName() << ", Marks: " << chemistryStudents[i].getChemistryMarks() << endl;
}

cout << "\nMaths Marks:\n";


for(int i = 0; i < n; i++) {
cout << "Roll Number: " << mathsStudents[i].getRollNumber() << ", Name: " <<
mathsStudents[i].getName() << ", Marks: " << mathsStudents[i].getMathsMarks() << endl;
}

int totalPhysicsMarks = 0, totalChemistryMarks = 0, totalMathsMarks = 0;


for(int i = 0; i < n; i++) {
totalPhysicsMarks += physicsStudents[i].getPhysicsMarks();
totalChemistryMarks += chemistryStudents[i].getChemistryMarks();
totalMathsMarks += mathsStudents[i].getMathsMarks();
}

cout << "\nAverage Marks:\n";


cout << "Physics: " << (double)totalPhysicsMarks / n << endl;
cout << "Chemistry: " << (double)totalChemistryMarks / n << endl;
cout << "Maths: " << (double)totalMathsMarks / n << endl;

return 0;
}
9. Assume that test results of a batch of students are stored in three different classes. Class
student stores the rollnum and name, class test will be inherited from student store the marks of
two tests. The sports class will be inherited from student will provide the sports weightage. The
result class inherited from test and student will add the test marks and sports weightage and
displays all the information. Write a C++ program for the same.
#include<iostream>
using namespace std;

class student {
public:
int rollnum;
string name;

void get_data() {
cout << "Enter the student name: ";
cin >> name;
cout << "Enter the student roll number: ";
cin >> rollnum;
}

void put_data() {
cout << "Student Name: " << name << endl;
cout << "Student Roll number: " << rollnum << endl;
}
};

class test: virtual public student {


public:
float test1, test2;

void get_test() {
cout << "Enter the test marks for the student with roll number " << rollnum << ":" << endl;
cout << "Test 1 is: ";
cin >> test1;
cout << "Test 2 is: ";
cin >> test2;
}

void put_test() {
cout << "The test marks for the student with roll number " << rollnum << " are: " << test1 << " and "
<< test2 << endl;
}
};

class sports: virtual public student {


public:
float sp_wt;

void get_spwt() {
cout << "Enter the sports weightage for the student with roll number " << rollnum << ":" << endl;
cin >> sp_wt;
}

void put_spwt() {
cout << "The sports weightage for the student with roll number " << rollnum << " is: " << sp_wt <<
endl;
}
};

class result: public test, public sports {


public:
float total;

void disp_res() {
total = test1 + test2 + sp_wt;
cout << "The total marks for the student with roll number " << rollnum << " is: " << total << endl;
}
};

int main() {
result r;
r.get_data();
r.get_test();
r.get_spwt();
r.put_data();
r.put_test();
r.put_spwt();
r.disp_res();
return 0;
}
10.Consider a book shop which sells both books and video tape. We can create a class known
as media that stores the title and price of the publications. We create two derived class, one for
storing the number of pages in a book and another for storing the playing time of a tape. A display
function is used in all the classes to display the class contents. Implement the program to the
same. (use of constructors in inheritance and virtual class).#include<iostream>
#include<string.h>
using namespace std;
class Media
{
protected:
string title;
float price;
public:
Media(string s,float p)
{
title=s;
price=p;
}
virtual void display(){
}
};
class book:public Media
{
int pages;
public:
book(string s,float a,int p):Media(s,a){
pages=p;
}
void display()
{
cout<<"\n Title of the book:"<<title<<endl;
cout<<"\n Price of the book:"<<price<<endl;
cout<<"\n Number of pages in the book:"<<pages<<endl;
}
};
class tape:public Media
{
float playtime;
public:
tape(string s,float a,float t):Media(s,a)
{
playtime=t;
}
void display()
{
cout<<"\n Title of the tape:"<<title<<endl;
cout<<"\n Price of the tape:"<<price<<endl;
cout<<"\n Play time of the tape:"<<playtime<<endl;
}
};
int main()
{
string title;
f
loat price,ptime;
int pages;
cout<<"\n Enter the details of the book:"<<endl;
cout<<"\n Enter Title of the book:";
cin>>title;
cout<<"\n Enter Price of the book:";
cin>>price;
cout<<"\n Enter Number of pages in the book:";
cin>>pages;
book b(title,price,pages);
cout<<"\n Enter the details of the tape:"<<endl;
cout<<"\n Enter Title of the tape:";
cin>>title;;
cout<<"\n Enter Price of the tape:";
cin>>price;
cout<<"\n Enter play time of the tape:";
cin>>ptime;
tape t(title,price,ptime);
Media* list[2];
list[0] = &b;
list[1] = &t;
cout<<"\n MEDIA DETAILS ARE:";
cout<<"\n*************BOOK***************\n";
list[0]->display();
cout<<"\n*************TAPE***************\n";
list[1]->display();
}
11..Write a program to swap two integer numbers, two floating point numbers, two double type #include
<iostream>

template <typename T>


class Swap {
public:
void swapValues(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
};

int main() {
int int1 = 5, int2 = 10;
float float1 = 3.5, float2 = 7.8;
double double1 = 12.34, double2 = 56.78;
char char1 = 'A', char2 = 'B';

Swap<int> intSwap;
Swap<float> floatSwap;
Swap<double> doubleSwap;
Swap<char> charSwap;

std::cout << "Before swapping:\n";


std::cout << "int1 = " << int1 << ", int2 = " << int2 << "\n";
std::cout << "float1 = " << float1 << ", float2 = " << float2 << "\n";
std::cout << "double1 = " << double1 << ", double2 = " << double2 << "\n";
std::cout << "char1 = " << char1 << ", char2 = " << char2 << "\n";

intSwap.swapValues(int1, int2);
floatSwap.swapValues(float1, float2);
doubleSwap.swapValues(double1, double2);
charSwap.swapValues(char1, char2);

std::cout << "\nAfter swapping:\n";


std::cout << "int1 = " << int1 << ", int2 = " << int2 << "\n";
std::cout << "float1 = " << float1 << ", float2 = " << float2 << "\n";
std::cout << "double1 = " << double1 << ", double2 = " << double2 << "\n";
std::cout << "char1 = " << char1 << ", char2 = " << char2 << "\n";

return 0;
}
12.Write bubble sort function to sort set of integers, set floating point number, set of double
type values and set of characters using template class.
#include <iostream>

template <typename T>


class BubbleSort {
public:
void sort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
};

int main() {
int intArr[] = {5, 3, 8, 4, 2};
float floatArr[] = {3.5, 7.8, 1.2, 9.9, 4.4};
double doubleArr[] = {12.34, 56.78, 23.45, 67.89, 34.56};
char charArr[] = {'B', 'A', 'D', 'C', 'E'};

int n = sizeof(intArr) / sizeof(intArr[0]);

BubbleSort<int> intBubbleSort;
BubbleSort<float> floatBubbleSort;
BubbleSort<double> doubleBubbleSort;
BubbleSort<char> charBubbleSort;

std::cout << "Before sorting:\n";


std::cout << "intArr = ";
for (int i = 0; i < n; i++) {
std::cout << intArr[i] << " ";
}
std::cout << "\n";
std::cout << "floatArr = ";
for (int i = 0; i < n; i++) {
std::cout << floatArr[i] << " ";
}
std::cout << "\n";

std::cout << "doubleArr = ";


for (int i = 0; i < n; i++) {
std::cout << doubleArr[i] << " ";
}
std::cout << "\n";

std::cout << "charArr = ";


for (int i = 0; i < n; i++) {
std::cout << charArr[i] << " ";
}
std::cout << "\n";

intBubbleSort.sort(intArr, n);
floatBubbleSort.sort(floatArr, n);
doubleBubbleSort.sort(doubleArr, n);
charBubbleSort.sort(charArr, n);

std::cout << "\nAfter sorting:\n";


std::cout << "intArr = ";
for (int i = 0; i < n; i++) {
std::cout << intArr[i] << " ";
}
std::cout << "\n";

std::cout << "floatArr = ";


for (int i = 0; i < n; i++) {
std::cout << floatArr[i] << " ";
}
std::cout << "\n";

std::cout << "doubleArr = ";


for (int i = 0; i < n; i++) {
std::cout << doubleArr[i] << " ";
}
std::cout << "\n";

std::cout << "charArr = ";


for (int i = 0; i < n; i++) {
std::cout << charArr[i] << " ";
}
std::cout << "\n";

return 0;
}

You might also like