C++ Lab Manual Final
C++ Lab Manual Final
LABORATORY MANUAL
Course Title : C++ Basics Lab
Course Code : BEC358C
Year / Semester : 2nd Year / 3rd Semester
Academic Year : 2023 - 24
Course In-Charge : Prof. Plasin Dias,
Prof. B N Choukimath,
Prof. Sheetal N. Mindolkar
Vision
To nurture talent & enrich society through excellence in technical education, research &
innovation.
Mission
1. To augment innovative Pedagogy & kindle quest for interdisciplinary learning & to enhance
conceptual understanding.
2. To build competence, professional ethics & develop entrepreneurial thinking.
3. To strengthen Industry Institute Partnership & explore global collaborations.
4. To inculcate culture of socially responsible citizenship.
5. To focus on Holistic & Sustainable development.
Vision
To bring out talented, skilled, and sustainable Electronics and Communication Engineering
Graduates through strong domain expertise to serve the Society with greater Professional Ethics.
Mission
1. To create and impart an active learning ambience to accomplish a high degree of Professional
competencies
2. To inculcate innovative research and developmental thinking in effective Teaching and
Learning processes for solving Societal challenges
3. To deliver the needs and requirements of the latest state of art of the Industry through
quality multidisciplinary internship and training programs
PEOs
Attain essential and adequate fundamental knowledge in the domain of Electronics
PEO 1: & Communication Engineering that prepares them for their future with respect
to Professional Careers / Higher Education
Utilize acquired skills, knowledge and expertise in designing innovative novel
PEO 2: technology through multidisciplinary approach so as to accomplish solutions to
real life challenges of Society
Provide scope for lifelong Learning & leadership qualities through effective
PEO 3: communication to attain higher work efficiency with appropriate and required
ethical practices
Course Title : C++ Basics Lab
Course Code : BEC358C
Year / Semester : 2nd Year / 3rd Semester
Academic Year : 2023 – 24
1. Write a C++ program to find largest, smallest & second largest of three numbers
using inline functions MAX & Min.
2. Write a C++ program to calculate the volume of different geometric shapes like
cube, cylinder and sphere using function overloading concept.
3. Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare
an array of 10 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.
4. Write a C++ program to create class called MATRIX using 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 + and – operators respectively. Display the results by overloading the
operator <<. If (m1==m2) them m3=m1+m2 and m4=m1-m2 else display error.
5. 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 inherits: Surname & Bank Balance feature from base class but provides
its own feature: First Name & DOB. Create & initialize F1 & S1 objects with
appropriate constructors & display the FATHER & SON details.
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.
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.
Syllabus :
Define a friend function for calculating the average marks using the method
mark_avg().
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.
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 = 123% of Basic, Income
Tax (IT) =30% of gross salary (=basic_ Salary_All_Allowances_IT).
10. Write a C++ program with different class related through multiple inheritance &
demonstrate the use of different access specified by means of members variables &
members functions.
11. 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.
12. Write a C++ program to implement exception handling with minimum 5 exceptions
classes including two built in exceptions.
1. Understand object-oriented programming concepts, and apply them in solving
problems.
2. To create, debug and run simple C++ programs.
CLOs :
3. Introduce the concepts of functions, friend functions, inheritance, polymorphism and
function overloading.
4. Introduce the concepts of exception handling and multithreading.
CO1: Write C++ program to solve simple and complex problems.
CO2: Apply and implement major object-oriented concepts like message passing,
function overloading, operator overloading and inheritance to solve real-world
COs :
problems.
CO3: Use major C++ features such as Templates for data type independent designs
and File I/O to deal with large data set.
CO4: Analyze, design and develop solutions to real-world problems applying OOP
concepts of C++.
COs CO1 CO2 CO3 CO4
CO / PO
: POs / PO1,2,3,4,5,6 PO1,2,3,4,5,6 PO1,2,3,4,5,6 PO1,2,3,4,5,6
Mapping PSOs PSO1 PSO1 PSO1 PSO1
Prof. Plasin Dias,
Course
: Prof. B N Choukimath,
In-Charge
Prof. Sheetal N. Mindolkar
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
1 2 3 2 1 1 1 1 -
2 2 3 2 1 1 1 1 -
3 2 3 2 1 1 1 1 -
4 2 3 2 1 1 1 1 -
To run a C++ program on your laptop, you will need a C++ compiler installed. Here are the general
steps:
cd /path/to/your/code
Copy code
This will create an executable file named my_program in the same directory.
7. View Output:
Your program should execute, and you will see the output in the terminal. That's it!
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.
PROGRAM:
#include<iostream>
#include<cmath>
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: ";
THEORY: In this program, three functions named volume are defined with different
parameters. The function 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 necessary 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:
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;
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:
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
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:" <<MAX_ROWS<<" x " <<MAX_COLS
<< endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> mat[i][j];
}
}
}
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;
}
OUTPUT:
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;
}
};
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;
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:
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;
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:
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;
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:
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;
Department of E&C Engineering, KLS – VDIT, HALIYAL Page 22
shapes[1] = ▵
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
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;
Department of E&C Engineering, KLS – VDIT, HALIYAL Page 24
cout << "gross salary: " << grossSalary << endl;
cout << "Income Tax: " <<incomeTax << endl;
cout << "Net Salary: " << netSalary << endl;
}
};
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
net salary 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
Salary Calculations of an Employee
Employee Number: 100
Employee Name: Bhaskar
Basic Salary: 23000
All Allowances: 28290
gross salary: 51290
Income Tax: 15387
Net Salary: 359
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();
Department of E&C Engineering, KLS – VDIT, HALIYAL Page 26
return 0;
}
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
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
Department of E&C Engineering, KLS – VDIT, HALIYAL Page 28
the this pointer.
OUTPUT:
PROGRAM:
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
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");
Department of E&C Engineering, KLS – VDIT, HALIYAL Page 30
// 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;
} catch (const CustomException2& e) {
cout << "Caught Custom Exception 2: " << e.what() << endl;
} catch (const CustomException3& e) {
cout << "Caught Custom Exception 3: " << e.what() << endl;
} catch (const exception& e) {
cout << "Caught Exception: " << e.what() << endl;
}
return 0;
}
OUTPUT: