Sodapdf
Sodapdf
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 (-)
Example: a - b
3. Multiplication (*)
Example: a * b
4. Division (/)
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 (%)
Example: a % b
2.assignment operators
1. Simple Assignment (=)
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
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
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.
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
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.
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.
2.comparison operators:
1. Equal To (==)
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 (||)
Example: a || b
3. Logical NOT (!)
The logical NOT operator ! returns the opposite of the operand.
Example: !a
class Operation {
private:
int a, b, add, sub, mul;
float div;
public:
inline void get() {
cout << "Enter two numbers: ";
cin >> a >> b;
}
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>
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;
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;
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;
// 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;
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();
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) {}
int main() {
// Creating an object using default constructor
Complex c1;
c1.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;
}
int main() {
Complex c1(3, 4);
Complex c2(2, 5);
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;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 4);
return 0;
}
5.Write a C++ program to demonstrate strcpy(),strcat() and strlen() function.
#include <iostream>
#include <cstring>
int main() {
char str1[50] = "reva, ";
char str2[50] = "presidency!";
char str3[50];
// 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>
int main() {
char str1[50] = "Hello";
char str2[50] = "Hello";
char str3[50] = "hello";
char str4[50] = "Goodbye";
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;
}
};
int main() {
Rectangle rect;
rect.setDimensions(5, 7);
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);
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;
}
};
int main() {
Shape* shapes[2];
Circle circle;
Square square;
shapes[0] = &circle;
shapes[1] = □
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
};
void draw() {
cout << "Drawing a circle." << endl;
}
void area() {
cout << "Area of the circle: " << 3.14 * radius * radius << endl;
}
};
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] = □
int main() {
int a = 10;
int b = -10;
return 0;
}
2.Write a C++ program to demonstrate the use of dec,oct and Hexa manipulators.
#include <iostream>
#include <iomanip>
int main() {
int decimal = 10;
int octal = 12;
int hexadecimal = 0xA;
return 0;
}
3. Write a C++ program to demonstrate the use of uppercase, nouppercase and setfill
manipulators.
#include <iostream>
#include <iomanip>
int main() {
double num = 123.456;
int width = 15;
return 0;
}
4.Write a C++ program to demonstrate the use of noshowpoint, showpoint, left and right
manipulators
#include <iostream>
#include <iomanip>
int main() {
double num = 123.456;
int width = 15;
return 0;
}
5. Write a C ++ program to add two numbers using function templates.
#include <iostream>
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;
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;
return 0;
}
7.Write a C++ program for Simple Calculator Using Class Templates.
#include <iostream>
using namespace std;
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;
return 0;
}
8.Write a C++ program to swap the integer values, float values and character using function
template.
#include <iostream>
using namespace std;
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;
return 0;
}
9. Write a C++ program to find maximum of two data items using function template.
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20;
cout << "Maximum of " << x << " and " << y << " is " << findMax(x, y) << 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;
}
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;
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
// 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;
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;
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;
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;
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];
}
}
}
}
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);
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;
}
int main() {
int l, b, h;
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;
}
int main() {
Student s;
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];
}
int main() {
Student students[5];
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();
}
int main() {
int 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();
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;
}
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;
}
}
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;
}
int main() {
Complex c1, c2, c3;
c1.input();
c2.input();
c3 = c1 + c2;
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;
}
};
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);
public:
Depositor() : accNo(0), balance(0.0) {}
void input() {
Customer::input();
public:
Borrower() : loanNo(0), loanAmt(0.0) {}
void input() {
Depositor::input();
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:
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>
public:
RectangleShape(float l, float b) : length(l), breadth(b) {}
float area() {
return length * breadth;
}
};
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>
public:
RectangleShape(float l, float b) : length(l), breadth(b) {}
float perimeter() {
return 2 * (length + breadth);
}
};
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>
public:
CircleShape(float r) : radius(r) {}
float area() {
return M_PI * radius * radius;
}
};
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>
public:
CircleShape(float r) : radius(r) {}
float circumference() {
return 2 * M_PI * radius;
}
};
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>
public:
Person(string n) : name(n) {}
void displayName() {
cout << "Name: " << name << endl;
}
};
public:
Student(string n, int r) : Person(n), rollNo(r) {}
void displayRollNo() {
cout << "Roll No: " << rollNo << endl;
}
};
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;
}
};
}
};
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; }
};
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>
class Length {
protected:
double len;
public:
Length(double len) : len(len) {}
double getLength() const { return len; }
};
int main() {
Breadth breadth(5.0);
Area area(10.0);
Perimeter perimeter(10.0);
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>
class Radius {
protected:
double rad;
public:
Radius(double rad) : rad(rad) {}
double getRadius() const { return rad; }
};
int main() {
Area area(5.0);
Circumference circumference(5.0);
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; }
};
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;
}
}
};
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>
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;
};
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>
class Shape {
protected:
double radius;
public:
Shape(double radius) : radius(radius) {}
virtual void calculateArea() const = 0;
virtual void calculateCircumference() const = 0;
};
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;
}
};
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);
}
};
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;
}
};
int main() {
Circle c;
c.get_data();
c.display();
return 0;
}
int main() {
int num1, num2;
float num3;
char str[100];
// Input Operations
cout << "Enter an integer: ";
cin >> num1;
// 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;
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;
original_num = num;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}
int main() {
Complex c1(3, 2);
Complex c2(1, 7);
Complex c3;
c3 = c1 + c2;
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) {}
int main() {
Time T1(3, 45);
Time T2(5, 30);
Time T3;
T3 = T1 + T2;
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";
}
}
int main() {
Matrix m1, m2, m3;
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) {}
void compute_interest() {
const double rate = 0.05; // 5% annual interest rate
double interest = balance * rate;
deposit(interest);
}
};
public:
CurrentAccount(std::string n, int num, double initial_balance, double charge)
: Account(n, num, initial_balance), service_charge(charge) {}
int main() {
SavingsAccount sa("John Doe", 12345, 5000);
sa.display_balance();
sa.deposit(1000);
sa.display_balance();
sa.compute_interest();
sa.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>
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;
int main() {
vector<Physics> physicsStudents;
vector<Chemistry> chemistryStudents;
vector<Maths> mathsStudents;
int n;
cout << "Enter the number of students: ";
cin >> n;
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;
}
};
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;
}
};
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;
}
};
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>
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;
intSwap.swapValues(int1, int2);
floatSwap.swapValues(float1, float2);
doubleSwap.swapValues(double1, double2);
charSwap.swapValues(char1, char2);
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>
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'};
BubbleSort<int> intBubbleSort;
BubbleSort<float> floatBubbleSort;
BubbleSort<double> doubleBubbleSort;
BubbleSort<char> charBubbleSort;
intBubbleSort.sort(intArr, n);
floatBubbleSort.sort(floatArr, n);
doubleBubbleSort.sort(doubleArr, n);
charBubbleSort.sort(charArr, n);
return 0;
}