Final C++ Manual
Final C++ Manual
Final C++ Manual
&
COMMUNICATION ENGINEERING
(2022 Scheme)
C++ Basics
BEC358C
Prepared By:
Lab Instructor:
Mr. Rakesh, Technical Staff, ECE
Approved by
Dr. Praveen J
IQAC Director, Professor and Head, ECE
C++ BASICS
Contents
SL. Page
Description
No No.
1 Vision and Mission of the Institute 1
3 Program Outcomes 3
4 Syllabus 5
5 CO-PO Mapping 7
Programs
To find largest, smallest & second largest of three numbers
6 8
using inline functions MAX & Min.
To calculate the volume of different geometric shapes like cube,
7 9
cylinder and sphere using function overloading concept.
Define a STUDENT class with USN, Name & Marks in 3 tests of
a subject. Declare an array of lO STUDENT objects. Using
8 appropriate functions, find the average of the two better marks 11
for each student. Print the USN, Name & the average marks of
all the students.
Write a C++ program to create a class called MATRIX using a
two-dimensional array of integers, by overloading the operator
== which checks the compatibility of two matrices to be added
9 and subtracted. Perform the addition and subtraction by 15
overloading the + and – operators respectively. Display the
results by overloading the operator <<. If (ml == m2) then m3 =
ml + m2 and m4 = ml – m2 else display error
Demonstrate simple inheritance concept by creating a base
class FATHER with data members: First Name, Surname, DOB
& bank Balance and creating a derived class SON, which
10 inherits: Surname & Bank Balance feature from base class but 18
provides its own feature: First Name & DOB. Create & initialize
Fl & Sl objects with appropriate constructors & display the
FATHER & SON details.
Write a C++ program to define class name FATHER & SON that
holds the income respectively. Calculate & display total income
11 20
of a family using Friend function.
C++ BASICS
1
lOMoAR cPSD| 30134443
2
lOMoAR cPSD| 30134443
Program Outcomes
Graduates of Electronics & Communication Engineering by the time of graduation
will demonstrate:
PO5: Modern tool usage: Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools including prediction and modelling
to complex engineering activities with an understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional engineering practice.
PO8: Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
PO12: Life-long learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context of
technological change.
4
lOMoAR cPSD| 30134443
5
lOMoAR cPSD| 30134443
6
lOMoAR cPSD| 30134443
Course objectives:
• Understand object-oriented programming concepts, and apply them in solving problems.
• To create, debug and run simple C++ programs.
• Introduce the concepts of functions, friend functions, inheritance, polymorphism and
function overloading.
• Introduce the concepts of exception handling and multithreading.
Course outcomes:
After studying this course, student will be able to
CO’S STATEMENTS
CO-PO mapping
Program
Course
Program Outcomes Specific
Outcomes
Outcomes
CO’S PO-1 PO-2 PO-3 PO-4 PO-5 PO-6 PO-7 PO-8 PO-9 PO-10 PO-11 PO-12 PSO-1 PSO-2
C208.1 3 3 3 - 2 - - - 2 - - 2 - 2
C208.2 2 2 2 - 2 - - - 2 - - 2 - 2
C208.3 3 3 3 - 2 - - - 2 - - 2 - 2
C208.4 2 2 2 - 2 - - - 2 - - 2 - 2
Sum 10 10 10 - 8 - - - 8 - - 8 - 8
Average 2.5 2.5 2.5 - 2 - - - 2 - - 2 - 2
7
lOMoAR cPSD| 30134443
1. Write a C++ program to find largest, smallest & second largest of three numbers using inline
functions MAX & Min.
Program:
#include<iostream>
using namespace std;
int main()
{
int num1, num2, num3;
return 0;
}
Theory: In this program, the MAX and MIN functions are defined as inline functions, which means that the
function body is substituted directly at the call site instead of being invoked as a separate function. This can
provide performance benefits for small functions like these.
The program prompts the user to enter three numbers and then uses the MAX and MIN functions to find
the largest and smallest numbers, respectively. The second largest number is calculated by subtracting
the largest and smallest numbers from the sum of all three numbers. Finally, the program outputs the
results.
OUTPUT:
Enter three numbers:
21 66 12
Largest: 66
Smallest: 12
Second Largest: 21
8
lOMoAR cPSD| 30134443
2. Write a C++ program to calculate the volume of different geometric shapes like cube, cylinder
and sphere using function overloading concept.
Program:
#include <iostream>
#include <math>
using namespace std;
const double PI = 3.14159;
int main()
{
int choice,rad;
double side, radius, height;
switch (choice)
{
case 1:
cout << "Enter the side length of the cube: ";
cin >> side;
cout << "Volume of the cube: " << volume(side) << endl;
break;
case 2:
cout << "Enter the radius of the cylinder: ";
cin >> radius;
cout << "Enter the height of the cylinder: ";
cin >> height;
cout << "Volume of the cylinder: " << volume(radius, height) << endl;
break;
9
lOMoAR cPSD| 30134443
case 3:
cout << "Enter the radius of the sphere: ";
cin >> rad;
cout << "Volume of the cylinder: " << volume(rad) << endl;
break;
cout << "Invalid choice!" << endl;
}
return 0;
}
Theory: In this program, three functions named volume are defined with different parameters. Thefunction
names are the same, but the parameters differ, which is known as function overloading. This allows us to
use the same function name for different geometric shapes.
The program prompts the user to select a shape (cube, cylinder, or sphere) and then takes the nece ssary
inputs (side length, radius, and height) accordingly. It then calls the appropriate overloaded volume function
based on the user's choice and outputs the calculated volume.
OUTPUT:
Select a shape to calculate the volume:
1. Cube
2. Cylinder
3. Sphere
Enter your choice (1-3): 1
Enter the side length of the cube: 3
Volume of the cube: 27
10
lOMoAR cPSD| 30134443
3. Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare an array of lO
STUDENT objects. Using appropriate functions, find the average of the two better marks for each
student. Print the USN, Name & the average marks of all the students.
Program:
#include <iostream>
#include <string>
using namespace std;
class STUDENT {
private:
string usn;
string name;
int marks[NUM_TESTS];
public:
void setDetails(const string& usn, const string& name, const int marks[]) {
this->usn = usn;
this->name = name;
for (int i = 0; i < NUM_TESTS; i++) {
this->marks[i] = marks[i];
}
}
double calculateAverage() {
int max1 = 0;
int max2 = 0;
void displayDetails() {
cout << "USN: " << usn <<endl;
cout << "Name: " << name << endl;
cout << "Average Marks: " << calculateAverage() << endl;
cout << endl;
}
};
int main() {
11
lOMoAR cPSD| 30134443
STUDENT students[NUM_STUDENTS];
return 0;
}
Theory: In this program, the STUDENT class has private member variables usn, name, and an array marks
to store the marks for each student. The class provides public member functions to set the details, calculate
the average of the two highest marks, and display the details of a student.
The program initializes an array of 10 STUDENT objects. It then prompts the user to enter the details for
each student, including the USN, name, and marks for 3 tests. The program calls the setDetails function to
set the details for each student. Finally, it displays the details (USN, name, and average marks) of all the
students using the displayDetails function.
OUTPUT:
12
lOMoAR cPSD| 30134443
Name: GANGA
Marks for 3 tests: 23
23
23
13
lOMoAR cPSD| 30134443
USN: 1BI21ET001
Name: GIRI
Average Marks: 12.5
USN: 1BI21ET002
Name: GURU
Average Marks: 44
USN: 1BI21ET003
Name: GANGA
Average Marks: 23
USN: 1BI21ET004
Name: THUNGA
Average Marks: 13.5
USN: 1BI21ET005
Name: RANGA
Average Marks: 24
USN: 1BI21ET006
Name: LAKSHMI
Average Marks: 23.5
USN: 1BI21ET007
Name: RASHMI
Average Marks: 23.5
USN: 1BI21ET008
Name: MOHAMMAD
Average Marks: 33.5
USN: 1BI21ET009
Name: JAMES
Average Marks: 23.5
USN: 1BI21ET010
Name: ROJA
Average Marks: 22
14
lOMoAR cPSD| 30134443
4. Write a C++ program to create a class called MATRIX using a two-dimensional array of integers,
by overloading the operator == which checks the compatibility of two matrices to be added and
subtracted. Perform the addition and subtraction by overloading the + and – operators respectively.
Display the results by overloading the operator <<. If (ml == m2) then m3 = ml + m2 and m4 =
ml – m2 else display error
Program:
#include <iostream>
using namespace std;
class MATRIX {
private:
int mat[MAX_ROWS][MAX_COLS];
int rows;
int cols;
public:
MATRIX(int rows, int cols) {
this->rows = rows;
this->cols = cols;
}
void inputMatrix() {
cout << "Enter the elements of the matrix:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> mat[i][j];
}
}
}
15
lOMoAR cPSD| 30134443
int main() {
MATRIX m1(MAX_ROWS, MAX_COLS);
MATRIX m2(MAX_ROWS, MAX_COLS);
if (m1 == m2) {
MATRIX m3 = m1 + m2;
MATRIX m4 = m1 - m2;
return 0;
}
Theory: This program creates two MATRIX objects, m1 and m2, with the specified number of rows and columns.
The user is prompted to enter the elements of each matrix using the inputMatrix() member function.
The program then checks if the matrices are compatible for addition and subtraction by overloading the
== operator. If they are compatible, it performs the addition and subtraction operations using the overloaded
+ and - operators, respectively.
The results are displayed using the overloaded << operator, which prints the matrix elements. If the
matrices are not compatible, an error message is displayed.
16
lOMoAR cPSD| 30134443
OUTPUT:
Enter the elements of Matrix 1:
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
Enter the elements of Matrix 2:
Enter the elements of the matrix:
2 1 2
1 1 1
1 2 1
Matrix 1 + Matrix 2:
3 3 5
5 6 7
8 10 10
Matrix 1 - Matrix 2:
-1 1 1
3 4 5
6 6 8
17
lOMoAR cPSD| 30134443
Program:
#include <iostream>
#include <string>
using namespace
std;class FATHER {
protected:
string surname;
double
bankBalance;
public:
FATHER(const string& surname, double bankBalance) : surname(surname),
bankBalance(bankBalance) {}
void displayFatherDetails()
{
cout << "Father's Surname: " << surname << endl;
cout << "Father's Bank Balance: $" << bankBalance << endl;
}
};
class SON : public FATHER
{
private:
string
firstName;string
dob;
public:
SON(const string& firstName, const string& dob, const string& surname, double
bankBalance)
: FATHER(surname, bankBalance), firstName(firstName), dob(dob) {}
void displaySonDetails()
{
cout << "Son's First Name: " << firstName << endl;cout << "Son's Date of Birth: " <<
dob << endl;
}
};
int main()
{
string fatherSurname, sonSurname, sonFirstName, sonDOB;
double fatherBankBalance, sonBankBalance;
cout << "Enter father's surname:
";cin >> fatherSurname;
cout << "Enter father's bank balance: $";
18
lOMoAR cPSD| 30134443
return 0;
}
Theory: In this program, the FATHER class is defined with data members for Surname and Bank Balance.
The SON class is derived from the FATHER class and adds data members for First Name and DOB. The
program creates objects F1 and S1 of the FATHER and SON classes, respectively, using appropriate
constructors.
The user is prompted to enter the details for the father (surname and bank balance) and the son (first name,
DOB, surname, and bank balance). The program then creates the objects F1 and S1 with the provided details.
Finally, the program displays the details of the father and son by calling the respective member functions
(displayFatherDetails() and displaySonDetails()).
OUTPUT:
Enter father's surname: raju
Enter father's bank balance: $2000
Enter son's first name: ganesh
Enter son's date of birth: 19-09-1982
Enter son's surname: raju
Enter son's bank balance: $250
Father Details:
Father's Surname: raju
Father's Bank Balance: $2000
Son Details:
Son's First Name: ganesh
Son's Date of Birth: 19-09-1982
19
lOMoAR cPSD| 30134443
6. Write a C++ program to define class name FATHER & SON that holds the income respectively.
Calculate & display total income of a family using Friend function.
Program:
#include <iostream>
using namespace std;
class FATHER {
private:
double income;
public:
FATHER(double income) : income(income) {}
class SON {
private:
double income;
public:
SON(double income) : income(income) {}
int main() {
double fatherIncome, sonIncome;
FATHER father(fatherIncome);
SON son(sonIncome);
cout << "Total family income: Rs." << totalIncome << endl;
return 0;
}
20
lOMoAR cPSD| 30134443
Theory: In this program, the FATHER class is defined with a private member variable income. The SON
class is also defined with a private member variable income. The friend function calculateTotalIncome is
declared in both classes.
The calculateTotalIncome function takes references to the FATHER and SON objects as arguments and
calculates the total income by adding their respective incomes. It has access to the private members of both
classes since it is declared as a friend function in both classes.
In the main function, the user is prompted to enter the incomes of the father and son. Objects of the FATHER
and SON classes are then created with the provided incomes. The calculateTotalIncome function is called
with these objects to calculate the total family income. Finally, the total income is displayed to the user.*/
OUTPUT:
Enter father's income: Rs.250000
Enter son's income: Rs.280000
Total family income: Rs.530000
21
lOMoAR cPSD| 30134443
7. Write a C++ program to accept the student detail such as name &3 different marks by get_data()
method & display the name & average of marks using display() method. Define a friend function
for calculating the average marks using the method mark_avg()
Program:
#include <iostream>
#include <string>
using namespace std;
class Marks {
private:
int mark1;
int mark2;
int mark3;
public:
Marks(int mark1, int mark2, int mark3) : mark1(mark1), mark2(mark2), mark3(mark3)
{}
class Student {
private:
string name;
Marks marks;
public:
Student(const string& name, int mark1, int mark2, int mark3)
: name(name), marks(mark1, mark2, mark3) {}
void display() {
cout << "Student Name: " << name << endl;
cout << "Average Marks: " << mark_avg(marks) << endl;
}
int main() {
string name;
int mark1, mark2, mark3;
22
lOMoAR cPSD| 30134443
student.display();
return 0;
}
Theory: In this program, there are two classes: Marks and Student. The Marks class holds the three
different marks, and the Student class holds the student's name and an object of the Marks class.
The Marks class has private member variables for three marks and a constructor to initialize them.
The Student class has private member variables for the student's name and an object of the Marks class.
It also has public member functions get_data() to accept the student's name and marks and display() to
display the name and average marks.
The friend function mark_avg() is defined in both classes. It takes a Student object as an argument and
calculates the average marks using the three marks stored in the Marks object of the Student object.
In the main() function, the user is prompted to enter the student's name and marks for three subjects.
The get_data() function is called to set the student's details. Finally, the display() function is called to
display the student's name and average marks using the mark_avg() friend function.
OUTPUT:
Enter student name: Harish
Enter marks for three subjects: 28
25
63
Student Name: Harish
Average Marks: 38.6667
23
lOMoAR cPSD| 30134443
8. Write a C++ program to explain virtual function (Polymorphism) by creating a base class polygon
which has virtual function areas two classes rectangle & triangle derived from polygon & they
have area to calculate & return the area of rectangle & triangle respectively.
Program:
#include <iostream>
using namespace std;
class Polygon {
public:
virtual double area() = 0; // Pure virtual function
public:
Rectangle(double length, double width) : length(length), width(width) {}
public:
Triangle(double base, double height) : base(base), height(height) {}
int main() {
Polygon* shapes[2];
shapes[0] = &rectangle;
shapes[1] = ▵
24
lOMoAR cPSD| 30134443
return 0;
}
Theory: the Polygon class has a virtual area() function, making it a polymorphic base class. The Rectangle
and Triangle classes inherit from Polygon and override the area() function with their own
implementations.
In the main() function, an array of Polygon pointers shapes is created. Objects of Rectangle and Triangle
are instantiated, and their addresses are stored in the shapes array. This allows polymorphic behavior, where
the appropriate area() function is called based on the actual object type, even though the function is called
through a base class pointer.
The program then iterates through the shapes array and calls the area() function for each shape, displaying
the calculated areas.*/
OUTPUT:
Shape 1 Area: 15
Shape 2 Area: 12
25
lOMoAR cPSD| 30134443
9. Design, develop and execute a program in C++ based on the following requirements: An EMPLOYEE
class containing data members & members functions: i) Data members: employee number (an
integer), Employee_ Name (a string of characters), Basic_ Salary (in integer), All Allowances (an
integer), Net Salary (an integer). (ii) Member functions: To read the data of an employee, to calculate
Net_Salary& to print the values of all the data members. (All Allowances
= l23% of Basic, Income Tax (IT) =3O% of gross salary (=basic_ Salary_All_Allowances_IT).
Program:
#include <iostream>
#include <string>
using namespace std;
class EMPLOYEE {
private:
int employeeNumber;
string employeeName;
int basicSalary;
int allAllowances;
int grossSalary;
int incomeTax;
int netSalary;
public:
void readData() {
cout << "Details of an Employee "<<endl;
cout << "Enter employee number: ";
cin >> employeeNumber;
cout << "Enter employee name: ";
cin.ignore(); // Ignore any previous newline character
getline(cin, employeeName);
cout << "Enter basic salary: ";
cin >> basicSalary;
}
void calculateNetSalary() {
allAllowances = static_cast<int>(1.23 * basicSalary); // 123% of Basic Salary
grossSalary = basicSalary + allAllowances;
incomeTax = static_cast<int>(0.3 * grossSalary); // 30% of Gross Salary
netSalary = grossSalary - incomeTax;
}
void printData() {
cout << endl;
cout << "Salary Calculations of an Employee"<<endl;
cout << "Employee Number: " << employeeNumber << endl;
cout << "Employee Name: " << employeeName << endl;
cout << "Basic Salary: " << basicSalary << endl;
cout << "All Allowances: " << allAllowances << endl;
cout << "gross salary: " << grossSalary << endl;
cout << "Income Tax: " << incomeTax << endl;
cout << "Net Salary: " << netSalary << endl;
}
};
26
lOMoAR cPSD| 30134443
int main() {
EMPLOYEE emp;
emp.readData();
emp.calculateNetSalary();
emp.printData();
return 0;
}
Theory: In this program, the EMPLOYEE class is defined with private member variables employeeNumber,
employeeName, basicSalary, allAllowances, and netSalary. The class also contains three member functions:
readData() to read the employee data, calculateNetSalary() to calculate the netsalary based on the given
formulas, and printData() to display the values of all data members.
In the main() function, an object emp of the EMPLOYEE class is created. The readData() function is called to
input the employee details. The calculateNetSalary() function is then called to calculate the net salary based
on the given formulas. Finally, the printData() function is called to display all the employee data.
OUTPUT:
Details of an Employee
Enter employee number: 100
Enter employee name: Bhaskar
Enter basic salary: 23000
27
lOMoAR cPSD| 30134443
lO. Write a C++ program with different class related to multiple inheritance &demonstrate the use
of different access specified by means of members variables & members functions.
Program:
#include <iostream>
using namespace std;
class Base1 {
protected:
int protectedData1;
public:
Base1(int data) : protectedData1(data) {}
void printBase1() {
cout << "Base1::protectedData1 = " << protectedData1 << endl;
}
};
class Base2 {
protected:
int protectedData2;
public:
Base2(int data) : protectedData2(data) {}
void printBase2() {
cout << "Base2::protectedData2 = " << protectedData2 << endl;
}
};
public:
Derived(int data1, int data2, int data3)
: Base1(data1), Base2(data2), privateData(data3) {}
void printDerived() {
printBase1(); // Accessing protected member of Base1
Base2::printBase2(); // Accessing protected member of Base2
cout << "Derived::privateData = " << privateData << endl;
}
};
int main() {
Derived derived(10, 20, 30);
derived.printDerived();
return 0;
}
28
lOMoAR cPSD| 30134443
Theory: In this program, we have three classes: Base1, Base2, and Derived. The Derived class is derived
from both Base1 and Base2, demonstrating multiple inheritance.
Base1 has a protected member variable protectedData1 and a member function printBase1() to print its value.
Base2 has a protected member variable protectedData2 and a member function printBase2() to print its value.
Derived inherits both Base1 and Base2. It also has a private member variable privateData of its own. The
printDerived() function is defined in Derived to access and print the values of the member variables from all
the classes.
In the main() function, an object derived of the Derived class is created. The printDerived() function is then
called to demonstrate the use of different access specifiers and access the member variables and member
functions of the respective classes.
Note that protected members are accessible within the class itself and by derived classes, while private
members are only accessible within the class itself.
OUTPUT:
Base1::protectedData1 = 10
Base2::protectedData2 = 20
Derived::privateData = 30
29
lOMoAR cPSD| 30134443
ll. Write a C++ program to create three objects for a class named count object with data members such
as roll_no & Name. Create a members function set_data ( ) for setting the data values & display ( )
member function to display which object has invoked it using this pointer
Program:
#include <iostream>
#include <string>
using namespace std;
class CountObject {
private:
int roll_no;
string name;
public:
void set_data(int rollNo, const string& studentName) {
roll_no = rollNo;
name = studentName;
}
void display() {
cout << "Object with roll_no " << roll_no << " and name " << name << " invoked
display()" << endl;
cout << "This pointer value: " << this << endl;
}
};
int main() {
CountObject obj1, obj2, obj3;
obj1.set_data(1, "Alice");
obj2.set_data(2, "Bob");
obj3.set_data(3, "Charlie");
obj1.display();
obj2.display();
obj3.display();
return 0;
}
Theory: In this program, the CountObject class is defined with private member variables roll_no and name.
It has member functions set_data() to set the data values and display() to display which object invoked it
using the this pointer.
In the main() function, three objects obj1, obj2, and obj3 of the CountObject class are created. The set_data()
function is called on each object to set the roll number and name. Then, the display() function is called on
each object to demonstrate the use of the this pointer and display which object invoked it.
The program outputs the roll number, name, and the memory address of the object using the this pointer.
30
lOMoAR cPSD| 30134443
OUTPUT:
Object with roll_no 1 and name Alice invoked display()
This pointer value: 0x7ffc5d2d1250
Object with roll_no 2 and name Bob invoked display()
This pointer value: 0x7ffc5d2d1280
Object with roll_no 3 and name Charlie invoked display()
This pointer value: 0x7ffc5d2d12b0
31
lOMoAR cPSD| 30134443
l2. Write a C++ program to implement exception handling with minimum 5 exceptions classes
including two built in exceptions.
Program:
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
class CustomException1 : public exception {
public:
const char* what() const noexcept override {
return "Custom Exception 1";
}
};
int main() {
try {
int choice;
cout << "Enter an option between 1 and 5: ";
cin >> choice;
switch (choice) {
case 1:
throw CustomException1();
case 2:
throw CustomException2();
case 3:
throw CustomException3();
case 4:
throw logic_error("Logic Error Exception");
// Built-in exception class
case 5:
throw out_of_range("Out of Range Exception");
// Built-in exception class
default:
throw runtime_error("Unknown Exception"); // Built-in exception class
}
} catch (const CustomException1& e) {
cout << "Caught Custom Exception 1: " << e.what() << endl;
32
lOMoAR cPSD| 30134443
return 0;
}
Theory: In this program, we have five exception classes: CustomException1, CustomException2, and
CustomException3, which are custom exception classes derived from exception, and logic_error and
out_of_range, which are built-in exception classes.
The program prompts the user to enter an option between 1 and 5. Depending on the user's choice, it throws
different exceptions:
If the choice is 1, it throws a CustomException1. If
the choice is 2, it throws a CustomException2. If
the choice is 3, it throws a CustomException3.
If the choice is 4, it throws a logic_error exception with a custom message.
If the choice is 5, it throws a out_of_range exception with a custom message.
If the choice is any other number, it throws a runtime_error exception with a custom message.
The catch block catches the exceptions in the following order: first, the custom exceptions
(CustomException1, CustomException2, and CustomException3), and then the catch block for the base class
exception. It prints the appropriate error message based on the caught exception.
Feel free to modify the program as per your requirements or add more custom exception classes to showcase
different exceptional cases.
OUTPUT:
Enter an option between 1 and 5: 3
Caught Custom Exception 3: Custom Exception 3
33