BEC358C-c++ Lab Manual-Updated
BEC358C-c++ Lab Manual-Updated
………………………………………..
C++ Basics III SEM
VISION
Don Bosco group of institutions shines brighter each day with a vision to achieve a world class status in
providing exceptionally excellent higher education in the field of Management, Technology and Applied
Science entrenched with Human Values.
MISSION
With a mission to provide refined high quality technical education and training to aspiring students, we at
Don Bosco, strive to impart exclusively valuable, academic knowledge relating to an array of professional
fields undertaken.
Our persistent efforts will evidently create and develop future technocrats and proficient business leaders
who will confidently attend to improve the quality of life for the current generation.
MISSION
To foster an intellectual and ethical environment in which both skill and spirit will thrive so as to impart
high quality education, training, and service with an international outlook. To create and develop
technocrats and business leaders who will strive to improve the quality of life.
MISSION
To provide an excellent learning opportunity for all students and staff to develop knowledge and skills
essential in enlightening the individual’s ability to think vitally and utilize Electronics in detail to meet the
technological challenges of tomorrow and to refine knowledge and understanding through research and
creative activities.
⮚ Program Educational Objective 1: To prepare students for graduate and postgraduate programmes so
as to make them succeed in careers related to Electronics & Communication Engineering fields.
⮚ Program Educational Objective 2: To provide students with strong foundation in fundamental
concepts required in mathematical, scientific and engineering fields to make them succeed in their
technical profession.
⮚ Program Educational Objective 3: To train students with a broad-based scientific and engineering
knowledge so as to comprehend, analyze, design, and create innovative products and solutions for the
real life problems.
⮚ Program Educational Objective 4: To inculcate in students strong professional ethics along with a
strong character to uphold the spiritual and cultural values, effective communication skills, teamwork
skills, multidisciplinary approach, and ability to relate engineering issues to broader social context.
⮚ Program Educational Objective 5: To provide an academic environment and ambience so as to make
the students aware of advanced technological growth leading to life-long learning needed for a successful
professional career, excellence and leadership
PROGRAMME OUTCOMES:
CONTENT LIST
SL. PAGE
EXPERIMENT NAME
NO. NO.
Write a C++ program to find largest, smallest & second largest of three numbers
1. using inline functions MAX & Min 05
Write a C++ program to calculate the volume of different geometric shapes like
2. 06
cube, 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 10 STUDENT objects. Using appropriate functions, find the average
3. of the two better marks for each student. Print the USN, Name & the average
07
marks
of all the students.
Write a C++ program to create class called MATRIX using two-dimensional array
of integers, by overloading the operator == which checks the compatibility of
4. two matrices to be added and subtracted. Perform the addition and subtraction 09
by overloading + and – operators respectively. Display the results by
overloading the
operator
Demonstrate simple inheritance concept by creating a base class FATHER with
data members: First Name, Surname, DOB & bank Balance and creating a
5. derived class SON, which inherits: Surname & Bank Balance feature from base 13
class but
provides its own feature: First Name & DOB. Create & initialize F1 & S1
objects with appropriate constructors & display the FATHER & SON details.
Write a C++ program to define class name FATHER & SON that holds the income
6. 15
respectively. Calculate & display total income of a family using Friend function.
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
7. display() method. Define a friend function for calculating the average marks
18
using the method mark_avg().
Write a C++ program to explain virtual function (Polymorphism) by creating a
base class polygon which has virtual function areas two classes rectangle &
8. 20
triangle derived from polygon & they have area to calculate & return the area of
rectangle & triangle respectively.
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),
9. 23
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).
Write a C++ program with different class related through multiple inheritance &
10. demonstrate the use of different access specified by means of members variables 25
& members functions.
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 ( )
11.
for setting the data values & display ( ) member function to display which object
28
has invoked it using „this‟ pointer
Program 1
Write a C++ program to find largest, smallest & second largest of three numbers using inline functions MAX & Min
#include<iostream>
using namespace std;
inline int max(int x,int y,int z)
{
if(x>y&&x>z)
return(x);
else if(y>z)
return(y);
else
return(z);
}
inline int min(int x,int y,int z)
{
if(x<y&&x<z)
return(x);
else if(y<z)
return(y);
else
return(z);
}
int main()
{
int a,b,c,seclargest;
cout<<" enter three numbers:"<< endl;
cin >>a>>b>>c;
cout<<max(a,b,c)<<" is larger" << endl;
cout<<min(a, b, c) <<"is smallest"<< endl;
seclargest=(a+b+c)-((max(a,b,c)+min(a,b,c)));
cout<<"second largest is"<<seclargest<<endl;
return(0);
}
Program2:
Write a C++ program to calculate the volume of different geometric shapes like cube, cylinder and sphere
using function overloading concept.
#include<iostream >
using namespace std;
float vol(int,int);
float vol(float);
int vol(int);
int main()
{
int r,h,a;
float r1;
cout<<"enter radius and height of a cylinder:";
cin>>r>>h;
cout<<"enterside of cube:";
cin>>a;
cout<<"enter radius of sphere:";
cin>>r1;
cout<<"volume of cylinder is"<<vol(r,h);
cout<<"\nvolume of cube is "<<vol(a);
cout<<"\n volume of sphere is: "<<vol(r1);
return 0;
}
float vol(int r, int h)
{
return(3.14*r*r*h);
}
float vol(float r1)
{
return((4*3.14*r1*r1*r1)/3);
}
int vol(int a)
{
return(a*a*a);
}
Program3:
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.
#include<iostream>
#include<string>
using namespace std;
class STUDENT
{
public:
string name,USN;
int s1,s2,s3;
void read()
{
std::cout<<"enter the name";
std::cin>>name;
std::cout<<"enter the sub1 marks";
std::cin>>s1;
std::cout<<"enter the sub2 marks";
std::cin>>s2;
std::cout<<"enter the sub3 marks";
std::cin>>s3;
}
void disp()
{
std::cout<<"\nName"<<name;
std::cout<<"\nUSN"<<USN;
std::cout<<"\n sub1
mks"<<s1; std::cout<<"\n
sub2 mks"<<s2; std::cout<<"\
n sub3 mks"<<s3;
}
void average()
{
int
m1,m2;
float avg;
if(s1>s2 && s1>s3)
{
m1=s1;
if(s2>s3)
m2=s2;
else m2=s3;
}
else if(s2>s3 && s2>s1)
if(s3>s1)
m2=s3;
else
m2=s1;
}
else
{
m1=s3;
if(s1>s2)
m2=s1;
else
m2=s2;
}
avg=(m1+m2)/2.0;
std::cout<<"\n the average marks"<<avg;
}
};
int main()
{
STUDENT A[10];
for(int i=0;i<3;i++)
{
std::cout <<"\n enter the details of "<<i+1<<"student\n";
A[i].read();
}
for(int i=0;i<3;i++)
{
std::cout <<"\nenter the details of "<<i+1<<"student\
n"; cout<<"-----";
A[i].disp();
}
for(int i=0;i<3;i++)
{
std:cout <<"\n average of "<<i+1<<"student\n";
A[i].average();
return 0;
}
Program 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
#include <iostream>
using namespace std;
class matrix
{
int a[3][3];
public:
void accept();
void display();
void operator+(matrix x);
void operator-(matrix x);
};
void matrix::accept()
{
cout<<"\n enter matrix element (3*3):\n";
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{
cout<<" ";
cin>>a[i][j];
}
}
}
void matrix::display()
{
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{
cout<<a[i][j]<<"\t" ;
}
cout<<"\n";
}
}
void matrix::operator+(matrix x)
{
int mat[3][3];
for(int i=0; i<3;i++)
{
for(int j=0; j<3;j++)
{
Output
First matrix
2 4 6
8 10 22
2 4 6
Second matrix
1 3 2
5 4 6
5 4 7
Addition of Matrices is :
3 7 8
13 14 28
7 8 13
Subtraction of Matrices is :
1 1 4
3 6 16
-3 0 -1
Program 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.
#include <iostream>
#include <string>
using namespace std;
class Father
{ protected:
string surname;
double bankBalance;
public:
Father (string surname, double bankBalance)
: surname(surname), bankBalance(Balance) {}
void displayFatherDetails() {
public:
Son(string firstName, string dob, string surname, double bankBalance)
: firstName(firstName), dob(dob), Father (surname, balance) {}
void displaySonDetails() {
cout << "\nSon’s Details:" << endl;
cout << "firstName:" << firstName<<endl;
cout << "Date of Birth: " << dob << endl;
cout << "Surname:" << Surname<<endl;
} };
int main ()
{
Son S1("John", "2000-05-10", "Smith", 2000.00);
Father F1("Smith", 50000.00);
S1. displaySonDetails();
F1. displayFatherDetails();
return 0;
}
Output:
Father's Details:
Surname: Smith
Bank Balance: $50000
Son's Details:
Surname: Smith
Bank Balance:
$2000 First Name:
John
Date of Birth: 2000-05-10
Program 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.
A friend function can access the private and protected data of a class. We declare a friend function
using the friend keyword inside the body of the class.
#include <iostream>
#include<conio.h>
using namespace std;
class father;
class son
{
private:
char name[15];
float income;
public:
void read();
void show();
friend void cal(father f,son s);
};
class father
{
private:
char name[15];
float salary;
public:
void read();
void show();
friend void cal(father f,son s);
};
void father::read()
{
cout<<"Enter name and salary ";
cin>>name>>salary;
}
void father::show()
{
cout<<name<<" "<<salary<<endl;
}
void son::read()
{
cout<<"Enter name and income ";
cin>>name>>income;
}
void son::show()
{
cout<<name<<" "<<income<<endl;
}
void cal(father f,son s)
{
float t;
t=f.salary+s.income;
cout<<"Total family income "<<t<<endl;
cout<<"Avg family income
"<<t/2<<endl;
}
int main()
{
father f1;
son s1;
f1.read();
s1.read();
f1.show();
s1.show();
cal(f1,s1);
return(0);
}
Output
Enter name and salary Amit
45000
Enter name and income Sunita
54000
Amit 45000
Sunita 54000
Total family income
99000 Avg family income
49500
Program 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().
#include<iostream>
#include<string>
using namespace std;
class Student{
string name;
int mark1, mark2, mark3;
public:
void get_data(){
cout << "Enter Name: ";
getline(cin, name);
cout << "Enter Marks in Subject 1: ";
cin >> mark1;
cout << "Enter Marks in Subject 2: ";
cin >> mark2;
cout << "Enter Marks in Subject 3: ";
cin >> mark3;
}
float mark_avg(Student s)
{
return (s.mark1 + s.mark2 + s.mark3)/3.0;
}
int main()
{ Student s;
s.get_data();
s.display();
return 0; }
Output:
In the above program, we have defined a class `Student` with member variables `name`, `mark1`,
`mark2`, and `mark3`. The member functions `get_data()` and `display()` are used to accept and display
the student details respectively.
The `mark_avg()` function is declared as a friend of the `Student` class. It takes a `Student` object as
input and calculates the average marks of the student by summing up the marks in three different subjects
and dividing by 3.
In the `main()` function, we create an object `s` of the `Student` class, call the `get_data()` function to
accept the student details, and then call the `display()` function to display the student name and average
marks calculated using the `mark_avg()` function.
Program 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.
#include <iostream>
using namespace
std;
class Polygon
{ protected:
double width, height;
public:
Polygon(double w, double h)
{ width = w;
height = h;
}
double area() {
cout << "Rectangle class area(): ";
return (width * height);
}
};
double area() {
cout << "Triangle class area(): ";
return (width * height / 2);
}};
DEPT OF ECE, DBIT Page 20
C++ Basics III SEM
int main() {
int RectLength, RectWidth, TriBase, TriHeight;
Polygon *poly1, *poly2;
cout<<"Enter the Length of RECT";
cin>>RectLength;
cout<<"Enter the width of RECT";
cin>>RectWidth;
cout<<"Enter the Base of TRI";
cin>>TriBase;
cout<<"Enter the Height of TRI";
cin>>TriHeight;
Rectangle rect(RectLength, RectWidth);
Triangle tri(TriBase, TriHeight);
poly1 = ▭
poly2 = &tri;
return 0;
}
Output:
Enter the Length of RECT 5
Enter the width of RECT 5
Enter the Base of TRI 3
Enter the Height of TRI 3
Rectangle class area(): 25
Triangle class area(): 10.5
C++ program to explain virtual functions (polymorphism) by creating a base class Polygon which has a
virtual function area(), and two derived classes Rectangle and Triangle that inherit from the Polygon
class and implement the area() function to calculate and return the area of rectangle and triangle
respectively.
In this program, we define a base class Polygon with two protected data members width and height and a
virtual function area(). The Rectangle and Triangle classes are derived from the Polygon class.
The area() function is defined as virtual in the Polygon class. This means that when a pointer of type
Polygon points to an object of the Rectangle or Triangle class, the correct version of the area() function is
called based on the type of the object being pointed to.
We then call the area() function using these pointers. The virtual function area() is called based on the
type of object being pointed to, so the correct version of area() is called for Rectangle and Triangle
objects respectively.
This is an example of polymorphism, where the same function name area() is used for both Rectangle and
Triangle classes, but they have different implementations, based on their individual needs.
Program 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).
#include <iostream>
#include <string>
using namespace std;
class Employee {
int empNumber, basicSalary, allowances, netSalary;
string empName;
public:
void readData() {
cout << "Enter Employee Number: ";
cin >> empNumber;
cout << "Enter Employee Name: ";
cin.ignore();
getline(cin, empName);
cout << "Enter Basic Salary:
"; cin >> basicSalary;
}
void calculateNetSalary()
{ allowances = 1.23 * basicSalary;
int grossSalary = basicSalary + allowances;
int incomeTax = 0.3 * grossSalary;
netSalary = grossSalary - incomeTax;
}
void printData() {
cout << "Employee Number: " << empNumber <<
endl; cout << "Employee Name: " << empName <<
endl; cout << "Basic Salary: " << basicSalary << endl;
cout << "Allowances: " << allowances <<
endl; cout << "Net Salary: " << netSalary <<
endl;
}};
int main()
{ Employee e;
e.readData();
e.calculateNetSalary();
e.printData();
return 0;
}
Output:
In the above program, we have defined an Employee class with data members empNumber,
empName, basicSalary, allowances, and netSalary. The member functions readData(),
calculateNetSalary(), and printData() are used to read the data of an employee, calculate the net
salary, and print the values of the data members respectively.
In the readData() function, we accept the employee number, employee name, and basic salary from
the user using cin and getline() functions.
In the calculateNetSalary() function, we calculate the allowances as 123% of the basic salary, and then
calculate the gross salary by adding the basic salary and allowances. We then calculate the income tax
as 30% of the gross salary and subtract it from the gross salary to get the net salary.
In the printData() function, we display all the data members of the Employee class using cout statements.
In the main() function, we create an object e of the Employee class, call the readData() function to accept
the employee details, then call the calculateNetSalary() function to calculate the net salary and finally call
the printData() function to display all the details.
Program 10
Write a C++ program with different class related through multiple inheritance & demonstrate the use of
different access specified by means of member’s variables & members functions.
Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class to inherit properties
or behaviour from multiple base classes. Therefore, we can say it is the process that enables a derived class
to acquire member functions, properties, characteristics from more than one base class.
#include <iostream>
using namespace
std;
// Base class
class Shape
{ public:
void displayShape() {
};
public:
void displayRectangle() {
};
{ public:
void displayCircle() {
};
public:
void displayRoundedRectangle() {
void displayShape() {
Rectangle::displayShape();
}};
int main() {
RoundedRectangle rr;
RoundedRectangle
Circle return 0;
Program 11
Write a C++ program to create three objects for a class named count object with data member 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
#include <iostream>
using namespace std;
class CountObject {
private:
int roll_no;
string name;
public:
void set_data(int roll, const string& studentName)
{ roll_no = roll;
name = studentName;
}
void display(string obj) {
Program 12
Write a C++ program to implement exception handling with minimum 5 exceptions classes including two
built in exceptions.
Exception handling in C++ consists of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
The catch statement allows you to define a block of code to be executed if an error occurs in the try block.
#include<iostream>
nt main()
int numerator,denominator,result;
cin>>numerator>>denominator;
try
if (denominator==0)
throw denominator;
result=numerator|denominator;
catch(int ex)
cout<<"division is:"<<result;
return 0;
Output:
Enter numerator and denominator
12
10
Division is : 1
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
char s1[6] = "Hello";
char s2[6] = "World";
char s3[12] = s1 + " " + s2;
cout<<s3;
return 0;
}