0% found this document useful (0 votes)
4 views

C++ LAB MANUAL (2)

The document outlines a C++ programming course with multiple experiments focused on different programming concepts. Key topics include using inline functions to find the largest, smallest, and second largest of three numbers, function overloading to calculate volumes of geometric shapes, creating a STUDENT class to compute average marks, and implementing a MATRIX class with operator overloading for matrix operations. Each experiment includes an aim, theory, algorithm, program code, and sample output.

Uploaded by

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

C++ LAB MANUAL (2)

The document outlines a C++ programming course with multiple experiments focused on different programming concepts. Key topics include using inline functions to find the largest, smallest, and second largest of three numbers, function overloading to calculate volumes of geometric shapes, creating a STUDENT class to compute average marks, and implementing a MATRIX class with operator overloading for matrix operations. Each experiment includes an aim, theory, algorithm, program code, and sample output.

Uploaded by

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

BEC358C C++ Basics

Experiment 1 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

Write a C++ program to find largest, smallest & second largest of three numbers
using inline functions MAX & Min

AIM: To find the largest, smallest, and second largest of three numbers using inline functions MAX
and Min.

THEORY:
Inline functions: C++ provides inline functions to reduce the function call overhead. An inline
function is a function that is expanded in line when it is called. When the inline function is called
whole code of the inline function gets inserted or substituted at the point of the inline function call.
This substitution is performed by the C++ compiler at compile time. An inline function may increase
efficiency if it is small.

Create inline functions MAX and Min to find the maximum and minimum of two numbers. Then,
using these functions, will determine the largest, smallest, and second largest numbers among the three
input numbers.

ALGORITHM:

 Start
 Define three variables num1, num2, and num3 to store the input numbers.
 Define an inline function int Max(int a, int b) to find the maximum of two numbers:
• If a > b, return a.
• Else, return b.
 Define an inline function int Min(int a, int b) to find the minimum of two numbers:
• If a < b, return a.
• Else, return b.
 Find the largest number among num1, num2, and num3 using the Max function:
• largest = Max(Max(num1, num2), num3)

Dept. of ECE, GSSSIETW, Mysuru Page 1


BEC358C C++ Basics

 Find the smallest number among num1, num2, and num3 using the Min function:
• smallest = Min(Min(num1, num2), num3)
 Find the second largest number among num1, num2, and num3:
• secondLargest = num1 + num2 + num3 - largest - smallest
 Print the largest, smallest, and secondLargest numbers.
 End
PROGRAM:

#include<iostream>
using namespace std;
inline int MAX (int a , int b , int c);
inline int Min(int a , int b , int c);

int main() {
int a , b ,c;
cout << "Enter three numbers : ";
cin >> a >> b >> c;
int Largest = MAX (a , b ,c);
cout << "\n Largest of " << a << " , " << b << " , " << c << " is " << Largest;
int smallest = Min (a , b ,c);
cout << "\n smallest of " << a << " , " << b << " , " << c << " is " << smallest;
int secondlargest = (a + b + c) - Largest - smallest;
cout << "\n second largest of " << a << " , " << b << " , " << c << " is " << secondlargest;
return 0;
}
inline int MAX (int a , int b , int c) {
if(a > b && a > c)
return a;
else if(b > c)
return b;
else
return c;
}
inline int Min (int a , int b , int c) {
if(a < b && a < c)
return a;
else if(b < c)
return b;
else

Dept. of ECE, GSSSIETW, Mysuru Page 2


BEC358C C++ Basics

return c;
}
OUTPUT:

Enter three numbers: 5 3 2


Largest of 5, 3, 2 is 5
smallest of 5 , 3 , 2 is 2
second largest of 5 , 3 , 2 is 3

Dept. of ECE, GSSSIETW, Mysuru Page 3


BEC358C C++ Basics

Experiment 2 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

Write a C++ program to calculate the volume of different geometric shapes like
cube, cylinder and sphere using function overloading concept.
AIM: To calculate the volume of various geometric shapes (cube, cylinder, and sphere) using the
concept of function overloading in C++.

THEORY: Function overloading in C++ allows you to define multiple functions with the same name
but different parameter lists. In this program, we'll define three functions named calculate Volume to
calculate the volume of a cube, cylinder, and sphere. Each function will have a different set of
parameters to accept the necessary inputs for the respective shape.
What is Overloading in C++?
C++ allows you to specify more than one definition for a function name or an operator in the same
scope, which is called function overloading and operator overloading respectively.
Function overloading:
We can have multiple definitions for the same function name in the same scope. The definition of the
function must differ from each other by the types and/or the number of arguments in the argument list.
We cannot overload function declarations that differ only by return type.

ALGORITHM:
 Start
 Define a function calculateVolume to calculate the volume of a cube with one parameter (side
length a).
• Calculate the volume of the cube: volume = a * a * a
 Define a function calculateVolume to calculate the volume of a cylinder with two parameters
(base radius r and height h).
• Calculate the volume of the cylinder: volume = π * r * r * h
 Define a function calculateVolume to calculate the volume of a sphere with one parameter
(radius r).

Dept. of ECE, GSSSIETW, Mysuru Page 4


BEC358C C++ Basics

• Calculate the volume of the sphere: volume = (4/3) * π * r * r * r


 In the main function:
• call the respective calculateVolume function with the required parameters.
• Display the calculated volume.
 End

PROGRAM:

#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<<"Enter side 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<<"\nVolume 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);
}

Dept. of ECE, GSSSIETW, Mysuru Page 5


BEC358C C++ Basics

OUTPUT:

Enter radius and height of a cylinder: 8 12


Enter side of cube: 2
Enter radius of sphere: 3

Volume of cylinder is 2411.52


Volume of cube is 8
Volume of sphere is 113.04

Dept. of ECE, GSSSIETW, Mysuru Page 6


BEC358C C++ Basics

Experiment 3 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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.
AIM: To create a STUDENT class with USN, Name, and marks in 3 tests, and then find and print the
average of the two better marks for each student using appropriate functions.

THEORY:

A class is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A C++ class is like a
blueprint for an object. A class is defined in C++ using the keyword class followed by the name of the
class.

Define a STUDENT class with three data members: USN, Name, and an array to store marks in 3
tests. Declare an array of 10 STUDENT objects to store information for multiple students. Using
appropriate member functions, and calculate the average of the two better marks for each student and
print the results.

ALGORITHM:

 Start
 Define a STUDENT class with the following data members:
• USN (string)
• Name (string)
• Marks (an array of 3 integers for three tests)
 Define a member function calculateAverage in the class to calculate the average of the two
better marks:
• Sort the marks in ascending order.
• Calculate the average of the two better marks.

Dept. of ECE, GSSSIETW, Mysuru Page 7


BEC358C C++ Basics

 In the main function:


• Declare an array of 10 STUDENT objects.
• Input the USN, Name, and marks for each student.
• For each student, call the calculateAverage function to find the average of the two
better marks.
• Print the USN, Name, and average marks for each student.
 End

PROGRAM:

#include<iostream>
using namespace std;
class Stu
{
char name[20],usn[5];
int marks[3];
float avg;
public:
void getdata();
void cal_avg();
void dis();
}obj[10];
void Stu::getdata()
{
cout<<"\n Enter the name: ";
cin>>name;

cout<<"\n Enter the USN: ";


cin>>usn;

cout<<"\n Enter the marks of 3 subject: ";


cin>>marks[0]>>marks[1]>>marks[2];
}
void Stu::cal_avg()
{
int i,j;
for(i=0; i<3; i++)
for(j=0; j<3-i-1; j++)
if(marks[j]>marks[j+1])

Dept. of ECE, GSSSIETW, Mysuru Page 8


BEC358C C++ Basics

{
int x;
x=marks[j];
marks[j]=marks[j+1];
marks[j+1]=x;
}
avg=(float)(marks[1]+marks[2])/2;
}
void Stu::dis()
{
cout<<"\n\nNAME : "<<name;
cout<<" | USN : "<<usn;
cout<<" | AVERAGE : "<<avg;
}
int main()
{
for(int i=0; i<10; i++)
{
obj[i].getdata();
obj[i].cal_avg();
}
for(int i=0;i<10;i++)
{
obj[i].dis();
}
return 0;
}

OUTPUT:

Enter the name: Anagha


Enter the USN: 22
Enter the marks of 3 subject: 23
34
45

Enter the name: Anamika


Enter the USN: 45
Enter the marks of 3 subject: 89

Dept. of ECE, GSSSIETW, Mysuru Page 9


BEC358C C++ Basics

90
89

NAME : Anagha | USN : 22 | AVERAGE : 39.5


NAME : Anamika | USN : 45 | AVERAGE : 89.5

Dept. of ECE, GSSSIETW, Mysuru Page 10


BEC358C C++ Basics

Experiment 4 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

Write a C++ program to create a class called MATRIX using a two dimensional
array of integers.Implement the following operations by overloading the operator
== which checks the compatibility of the two matrices to be added and subtracted.
Perform the addition and subtraction by overloading the operators + and -
respectively. Display the results by overloading operator <<.
AIM: To create a class called MATRIX using a two dimensional array of integers.Implement the
following operations by overloading the operator == which checks the compatibility of the two
matrices to be added and subtracted. Perform the addition and subtraction by overloading the operators
+ and - respectively. Display the results by overloading operator <<.

THEORY:

A two-dimensional array in C++ is the simplest form of a


multi-dimensional array. It can be visualized as an array of
arrays. The image below depicts a two-dimensional array. A
two-dimensional array is also called a matrix. It can be of any
type like integer, character, float, etc. depending on the
initialization.

Operator overloading is a compile-time polymorphism in which the operator is overloaded to


provide the special meaning to the user-defined data type. Operator overloading is used to overload or
redefines most of the operators available in C++. It is used to perform the operation on the user-
defined data type. For example, C++ provides the ability to add the variables of the user-defined data
type that is applied to the built-in data types.

ALGORITHM:

1. Start
2. Define the MATRIX class:
• Include a private two-dimensional array to store matrix elements.

Dept. of ECE, GSSSIETW, Mysuru Page 11


BEC358C C++ Basics

• Include public methods for input, output, and operator overloading.


3. Overload the == operator:
• Check if two matrices have the same dimensions.
4. Get the data for the no. of rows, no. of columns and matrix values from the user
5. Overload the + operator:
• Add corresponding elements of two matrices.
• Returns the resulting matrix.
6. Overload the - operator:
• Subtract corresponding elements of two matrices.
• Returns the resulting matrix.
7. Overload the << operator:
• Display the matrix elements in a formatted manner.
8. Main Function
• Create two matrix M1 and M2.
• Check if the matrices are compatible for addition and subtraction using operator ==
• If compatible, perform addition and subtraction using operator + and operator –
respectively
• Display the results using <<.

9. End

PROGRAM:

include<iostream.h>
#include<conio.h>
using namespace std;

class matrix
{
private:long m[5][5];
int row;int col;
public:void getdata();
int operator ==(matrix);
matrix operator+(matrix);
matrix operator-(matrix);
friend ostream & operator << (ostream &,matrix &);
Dept. of ECE, GSSSIETW, Mysuru Page 12
BEC358C C++ Basics

};
/* function to check whether the order of matrix are same or not */
int matrix::operator==(matrix cm)
{
if(row==cm.row && col==cm.col)
{
return 1;
}
return 0;
}

/* function to read data for matrix*/


void matrix::getdata()
{
cout<<"enter the number of rows\n";
cin>>row;
cout<<"enter the number of columns\n";
cin>>col;
cout<<"enter the elements of the matrix\n";
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
cin>>m[i][j];
}
}
}

/* function to add two matrix */


matrix matrix::operator+(matrix am)
{
matrix temp;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
temp.m[i][j]=m[i][j]+am.m[i][j];
}
temp.row=row;
temp.col=col;
}

Dept. of ECE, GSSSIETW, Mysuru Page 13


BEC358C C++ Basics

return temp;
}

/* function to subtract two matrix */


matrix matrix::operator-(matrix sm)
{
matrix temp;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
temp.m[i][j]=m[i][j]-sm.m[i][j];
}
temp.row=row;
temp.col=col;
}
return temp;
}

/* function to display the contents of the matrix */


ostream & operator <<(ostream &fout,matrix &d)
{
for(int i=0;i<d.col;i++)
{
for(int j=0;j<d.col;j++)
{
fout<<d.m[i][j];
cout<<" ";
}
cout<<endl;
}
return fout;
}

/* main function */
int main()
{
matrix m1,m2,m3,m4;
m1.getdata();
m2.getdata();
if(m1==m2)

Dept. of ECE, GSSSIETW, Mysuru Page 14


BEC358C C++ Basics

{
m3=m1+m2;
m4=m1-m2;
cout<<"Addition of matrices\n";
cout<<"the result is\n";
cout<<m3;
cout<<"subtraction of matrices\n";
cout<<"The result is \n";
cout<<m4;
}
else
{
cout<<"order of the input matrices is not identical\n";
}
return 0;
}

OUTPUT:

Case 1:
enter the number of rows
2
enter the number of columns
3
enter the elements of the matrix
123456
enter the number of rows
3
enter the number of columns
2
enter the elements of the matrix
1
2
3
4
5
6
order of the input matrices is not identical

Case 2:
enter the number of rows

Dept. of ECE, GSSSIETW, Mysuru Page 15


BEC358C C++ Basics

3
enter the number of columns
3
enter the elements of the matrix
9
8
7
6
5
4
3
2
1
enter the number of rows
3
enter the number of columns
3
enter the elements of the matrix
1
2
3
4
5
6
7
8
9
Addition of matrices
the result is
10 10 10
10 10 10
10 10 10
subtraction of matrices
The result is
864
2 0 -2
-4 -6 -8

Dept. of ECE, GSSSIETW, Mysuru Page 16


BEC358C C++ Basics

Experiment 5 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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.
AIM: To 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.

THEORY:

The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object Oriented Programming
in C++. Mode of inheritance controls the access level of the inherited members of the base class in the
derived class. In C++, there are 3 modes of inheritance:
 Public Mode
 Protected Mode
 Private Mode
During inheritance, the data members of the base class get copied in the derived class and can be
accessed depending upon the visibility mode used. The order of the accessibility is always in a
decreasing order i.e., from public to protected. There are mainly five types of Inheritance in C++ that
you will explore in this article. They are as follows:

 Single Inheritance
 Multiple Inheritance
 Multilevel Inheritance

Dept. of ECE, GSSSIETW, Mysuru Page 17


BEC358C C++ Basics

 Hierarchical Inheritance
 Hybrid Inheritance
Inheritance is used when two classes in a program share the same domain, and the properties of the
class and its superclass should remain the same. Inheritance is a technique used in C++ to reuse code
from pre-existing classes. C++ actively supports the concept of reusability.

ALGORITHM:

1. Start

2. Define the FATHER class:

o Declareprotected data members:

 First name
 Dob
 Surname
 Bank balance

o Define a public constructor FATHER() to input values.

o Define a public method disp1() to display the FATHER's details.

3. Define the SON class, which inherits from FATHER:

o Declare private data members:

 First name of the son.


 dob of the son.
o Define a public constructor SON() to input values.

o Define a public method disp() to display the SON's details.

4. In the main() function:

o Create an object s of class SON.

o Calls.disp1() to display the father's details.

o Calls.disp() to display the son's details.

5. End

Dept. of ECE, GSSSIETW, Mysuru Page 18


BEC358C C++ Basics

PROGRAM:

#include<iostream>
using namespace std;

// Base Class FATHER


class FATHER
{
protected:
char fname[20], dob[20];
char surname[20];
double bal;

public:
FATHER()
{
cout<< "enter first name of father\n";
cin>>fname;
cout<< "enter sur name of father\n";
cin>>surname;
cout<< "enter date of birth of father\n";
cin>>dob;
cout<< "enter bank balance of father\n";
cin>>bal;
}

void disp1()
{
cout<< "FATHER FIRST NAME IS" <<fname<< "\n";
cout<< "FATHER SUR NAME IS" << surname << "\n";
cout<< "FATHER DATE OF BIRTH IS" << dob << "\n";
cout<< "BANK BALANCE IS" <<bal<< "\n";
}
};

// Derived class SON


class SON : public FATHER
{
char fname[20], dob[20];
public:
void SON()
{
cout<< "enter first name of son\n";
cin>>fname;
cout<< "enter date of birth of son\n";

Dept. of ECE, GSSSIETW, Mysuru Page 19


BEC358C C++ Basics

cin>>dob;
}
void disp()
{
cout<< " name of son is" <<fname<< "\n";
cout<< " sur name is" << surname << "\n";
cout<< " son date of birth is" << dob << "\n";
cout<< " son bank balance is" <<bal<< "\n";
}
};

//main program

int main()
{
SON s;
s.disp1();
s.disp();
return 0;
}

OUTPUT:

enter first name of father


RAMU
enter sur name of father
NAIDU
enter date of birth of father
10/03/1945
enter bank balance of father
123456
enter first name of son
JAY
enter date of birth of son
21/04/1973
FATHER FIRST NAME IS RAMU
FATHER SUR NAME IS NAIDU
FATHER DATE OF BIRTH IS 10/03/1945
BANK BALANCE IS 123456
Dept. of ECE, GSSSIETW, Mysuru Page 20
BEC358C C++ Basics

name of son is JAY


sur name is NAIDU
son date of birth is 21/04/1973
son bank balance is 123456

Dept. of ECE, GSSSIETW, Mysuru Page 21


BEC358C C++ Basics

Experiment 6 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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.

AIM: To define class name FATHER & SON that holds the income respectively. Calculate & display
total income of a family using Friend function.

THEORY:

Friend functions: A friend function is a function that isn't a member of a class but has access to the
class's private and protected members. Friend functions aren't considered class members; they're
normal external functions that are given special access privileges. Friends aren't in the class's scope,
and they aren't called using the member-selection operators (. and ->) unless they're members of
another class. A friend function is declared by the class that is granting access. The friend declaration
can be placed anywhere in the class declaration. It isn't affected by the access control keywords.

ALGORITHM:

1. Start
2. Define class FATHER:
 Define data members, member function, declare friend function
3. Define class SON:
 Define data members, member function, declare friend function
4. Define friend function to access income of father and son
 Calculate total income
5. Define main function
 Create objects of FATHER & SON
 Call friend function to calculate sum of income and display.
6. End

Dept. of ECE, GSSSIETW, Mysuru Page 22


BEC358C C++ Basics

PROGRAM:

#include <iostream>
using namespace std;
class SON; // Forward declaration

class FATHER
{
private:
float fatherIncome;
public:
FATHER(float income = 0) : fatherIncome(income) {}
// Friend function declaration
friend float calculateTotalIncome(FATHER, SON);
};

class SON
{
private:
float sonIncome;
public:
SON(float income = 0) : sonIncome(income) {}
// Friend function declaration
friend float calculateTotalIncome(FATHER, SON);
};

// Friend function definition


float calculateTotalIncome(FATHER f, SON s)
{
return f.fatherIncome + s.sonIncome;
}

int main()
{
float fatherIncome, sonIncome;
// Input incomes

cout<< "Enter the father's income: ";


cin>>fatherIncome;
cout<< "Enter the son's income: ";
cin>>sonIncome;

// Create objects with the entered incomes

Dept. of ECE, GSSSIETW, Mysuru Page 23


BEC358C C++ Basics

FATHER father(fatherIncome);
SON son(sonIncome);
// Calculate and display total income using the friend function

float totalIncome = calculateTotalIncome(father, son);


cout<< "The total income of the family is: " <<totalIncome<<endl;
return 0;
}

OUTPUT:

Enter the father's income: 123456


Enter the son's income: 54321
The total income of the family is: 177777

Dept. of ECE, GSSSIETW, Mysuru Page 24


BEC358C C++ Basics

Experiment 7 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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().
AIM: 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 functionfor calculating the
average marks using the method mark_avg().

THEORY:

friend functions: A friend function is a function that isn't a member of a class but has access to the
class's private and protected members. Friend functions aren't considered class members; they're
normal external functions that are given special access privileges. Friends aren't in the class's scope,
and they aren't called using the member-selection operators (. and ->) unless they're members of
another class. A friend function is declared by the class that is granting access. The friend declaration
can be placed anywhere in the class declaration. It isn't affected by the access control keywords.

ALGORITHM:

1. Start
2. Define the Student class:
a. Declare the private data members: name, mark1, mark2, and mark3.
b. Define the public methods:
i. get_data(): to input the student's name and marks.
ii. display() const: to output the student's name and average marks.
iii. Declare a friend function mark_avg() to calculate the average marks.
3. Define get_data() method:
a. Prompt the user to input the student's name.
b. Prompt the user to enter three marks (mark1, mark2, mark3).
c. Store these inputs in the corresponding data members.
Dept. of ECE, GSSSIETW, Mysuru Page 25
BEC358C C++ Basics

4. Define mark_avg() friend function:


a. Take a constant reference to a Student object as input.
b. Access the mark1, mark2, and mark3 members of the Student object.
c. Calculate the average by summing the three marks and dividing by 3.
d. Return the calculated average as a float.
5. Define display() method:
a. Output the student's name.
b. Call mark_avg(*this) to calculate the average of the marks for the current Student object.
c. Output the returned average.
6. In the main() function:
a. Create a Student object.
b. Call get_data() on the Student object to input the student's details.
c. Call display() on the Student object to output the student's name and average marks.
7. End

PROGRAM:

#include <iostream>
using namespace std;
class Student {
private:
char name[20];
float mark1, mark2, mark3;
public:
// Method to get student details
void get_data() {
cout<< "Enter student's name: ";
cin>>name;
cout<< "Enter mark 1: ";
cin>>mark1;
cout<< "Enter mark 2: ";
cin>>mark2;
cout<< "Enter mark 3: ";
cin>>mark3;
}

Dept. of ECE, GSSSIETW, Mysuru Page 26


BEC358C C++ Basics

// Friend function to calculate average


friend float mark_avg( const Student& student);
// Method to display student's name and average marks
void display() const {
cout<< "Name: " << name <<endl;
cout<< "Average Marks: " <<mark_avg(*this) <<endl;
}
};
// Definition of friend function to calculate the average
float mark_avg(const Student& student) {
return (student.mark1 + student.mark2 + student.mark3) / 3;
}
int main()
{
Student student;
student.get_data(); // Input student details
student.display(); // Display name and average marks
return 0;
}

OUTPUT:

Enter student's name: Raadya


Enter mark 1: 89
Enter mark 2: 97
Enter mark 3: 96
Name: Raadya
Average Marks: 94

Dept. of ECE, GSSSIETW, Mysuru Page 27


BEC358C C++ Basics

Experiment 8 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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.
AIM: 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.

THEORY:
Virtual Functions and Runtime Polymorphism
A virtual function is a member function that is declared in the base class using
the keyword virtual and is re-defined (Overridden) in the derived class. It tells the
compiler to perform late binding where the compiler matches the object with the
right called function and executes it during the runtime. This technique falls under
Runtime Polymorphism.
The term Polymorphism means the ability to take many forms. It occurs if there
is a hierarchy of classes that are all related to each other by inheritance. In simple
words, when we break down Polymorphism into ‘Poly – Many’ and ‘morphism –
Forms’ it means showing different characteristics in different situations.

ALGORITHM:

1. Start
2. Define the Base Class:
 Create a class named Polygon.
 Add protected members width and height to store dimensions.
 Create a setDimensions() method to initialize width and height.
 Declare a virtual function area() to calculate the area. This will be overridden in the
derived classes.
Dept. of ECE, GSSSIETW, Mysuru Page 28
BEC358C C++ Basics

3. Define Derived Classes:

 Create a class Rectangle derived from Polygon.


o Override the area() function to compute the area of a rectangle using the formula:
area=width×height\text{area} = \text{width} \times
\text{height}area=width×height.

 Create a class Triangle derived from Polygon.


o Override the area() function to compute the area of a triangle using the formula:
area=0.5×width×height\text{area} = 0.5 \times \text{width} \times
\text{height}area=0.5×width×height.

4. Set Up Polymorphism:
 Use a base class pointer (Polygon*) to refer to objects of the derived classes.
 Call the area() function via the base class pointer, ensuring dynamic dispatch (runtime
polymorphism).
5. Implementation Steps:
 Create objects for Rectangle and Triangle.
 Use the setDimensions() method to initialize dimensions.
 Assign the address of each object to the base class pointer.
 Call the area() function through the base class pointer and display the result.
6. End

PROGRAM:

#include <iostream>
using namespace std;
// Base class
class Polygon{
protected:
double width, height;

public:
// Function to set dimensions
void setDimensions(double w, double h) {
width = w;

Dept. of ECE, GSSSIETW, Mysuru Page 29


BEC358C C++ Basics

height = h;
}

// Virtual function for calculating area


virtual double area() {
return 0.0; // Default area (to be overridden in derived classes)
}
// Virtual destructor (optional for polymorphism)
virtual ~Polygon() {}
};

// Derived class: Rectangle


class Rectangle : public Polygon {
public:
// Override the area method
double area() override {
return width * height;
}
};
// Derived class: Triangle
class Triangle : public Polygon {
public:
// Override the area method
double area() override {
return 0.5 * width * height;
}
};

int main() {
// Create pointers to the base class
Polygon *polygonPtr;

// Create Rectangle object


Rectangle rect;
polygonPtr = &rect; // Point to the rectangle object
Dept. of ECE, GSSSIETW, Mysuru Page 30
BEC358C C++ Basics

polygonPtr->setDimensions(8.0, 12.0); // Set width and height


cout << "Area of Rectangle: " << polygonPtr->area() << endl;

// Create Triangle object


Triangle tri;
polygonPtr = &tri; // Point to the triangle object
polygonPtr->setDimensions(9.0, 16.0); // Set width and height
cout << "Area of Triangle: " << polygonPtr->area() << endl;

return 0;
}

OUTPUT:

Area of Rectangle: 96
Area of Triangle: 72

Dept. of ECE, GSSSIETW, Mysuru Page 31


BEC358C C++ Basics

Experiment 9 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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).
AIM: To 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).

THEORY:

How the Salary Calculation Works:

1. All Allowances: 123% of basic salary


For Basic Salary = 50000, All Allowances = 50000 * 1.23 = 61500.

2. Gross Salary: Basic Salary + All Allowances


Gross Salary = 50000 + 61500 = 111500.

3. Income Tax: 30% of Gross Salary


Income Tax = 111500 * 0.30 = 33450.

4. Net Salary: Gross Salary - Income Tax


Net Salary = 111500 - 33450 = 78050.

Dept. of ECE, GSSSIETW, Mysuru Page 32


BEC358C C++ Basics

ALGORITHM:

1. Start the program.


2. Create the Employee class:
 Attributes:
o employeeNumber: Read an integer for the employee number.
o employeeName: Read a string for the employee's name.
o basicSalary: Read an integer for the basic salary of the employee.
o allAllowances: To store the calculated allowances (123% of the basic salary).
o netSalary: To store the final net salary (after deduction of income tax).

 Member Functions:
o readData():
 Input employee number.
 Input employee name.
 Input basic salary.

o calculateNetSalary():
 Compute allAllowances as 123% of the basicSalary.
 Compute grossSalary as the sum of basicSalary and allAllowances.
 Compute incomeTax as 30% of grossSalary.
 Compute netSalary as grossSalary - incomeTax.
o printData():
 Display the employee number.
 Display the employee name.
 Display the basic salary.
 Display the calculated all allowances.
 Display the calculated net salary.
3. In main():
 Create an object emp of the Employee class.
 Call emp.readData() to read the employee's input.
 Call emp.calculateNetSalary() to compute the net salary.

Dept. of ECE, GSSSIETW, Mysuru Page 33


BEC358C C++ Basics

 Call emp.printData() to display the employee details.


4. End the program.

PROGRAM:

#include <iostream>
using namespace std;

class Employee
{
private:
int employeeNumber;
char employeeName[20];
int basicSalary;
int allAllowances;
int netSalary;

public:
// Function to read data of an employee

void readData()
{
cout << "Enter Employee Number: ";
cin >> employeeNumber;
cout << "Enter Employee Name: ";
cin>>employeeName;
cout << "Enter Basic Salary: ";
cin >> basicSalary;
}

//Funtion to calculate net salary

void calculateNetSalary()
{
allAllowances = static_cast<int>(basicSalary * 1.23);
int grossSalary = basicSalary + allAllowances;
int incomeTax = static_cast<int>(grossSalary * 0.30);
netSalary = grossSalary - incomeTax;
}

// Function to print the employee details

void printData() const

Dept. of ECE, GSSSIETW, Mysuru Page 34


BEC358C C++ Basics

{
cout << "\nEmployee Details:\n";
cout << "Employee Number: " << employeeNumber << endl;
cout << "Employee Name: " << employeeName << endl;
cout << "Basic Salary: " << basicSalary << endl;
cout << "All Allowances: " << allAllowances << endl;
cout << "Net Salary: " << netSalary << endl;
}
};

// Main Program
int main()
{
Employee emp;
emp.readData();
emp.calculateNetSalary();
emp.printData();
return 0;
}

OUTPUT:

Enter Employee Number: 7894E


Enter Employee Name: Enter Basic Salary: 58746

Employee Details:
Employee Number: 7894
Employee Name: E
Basic Salary: 58746
All Allowances: 72257
Net Salary: 91703

Dept. of ECE, GSSSIETW, Mysuru Page 35


BEC358C C++ Basics

Experiment 10 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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.
AIM: To 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.

THEORY:

Multiple Inheritance is the concept of the Inheritance in C++ that allows a child class to inherit
properties or behavior 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.
In the above diagram, there are two-parent classes: Base
Class 1 and Base Class 2, whereas there is only one Child
Class. The Child Class acquires all features from both Base class 1 and Base class 2. Therefore, we
termed the type of Inheritance as Multiple Inheritance.

ALGORITHM:

1. Start the program.


 Include necessary header files and declare the namespace
2. Define the Base Class 1 (Vehicle)
 Declare a constructor for the class
 In the constructor, print the message: "This is a Vehicle.”
3. Define the Base Class 2 (Four Wheeler)
 Declare a constructor for the class.
 In the constructor, print the message: "This is a Four Wheeler.”

Dept. of ECE, GSSSIETW, Mysuru Page 36


BEC358C C++ Basics

4. Define the Derived Class (Car)


 Inherit Vehicle and Four Wheeler classes publicly.
 Declare a constructor for the class
 In the constructor, print the message: "This is a Four Wheeler Vehicle is a Car.”
5. Define the main function
 Create an object of the Car class, named obj.
 When the object is created:
o The constructors of the base classes (Vehicle and FourWheeler) are invoked in the
order of inheritance.
o The constructor of the derived class (Car) is invoked after the base class
constructors
 The messages are printed in the order of constructor calls.
5. End the program.

PROGRAM:

#include <iostream>
using namespace std;

//Base class 1

class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// Base class 2

class FourWheeler
{

Dept. of ECE, GSSSIETW, Mysuru Page 37


BEC358C C++ Basics

public:
FourWheeler()
{
cout << "This is a Four Wheeler\n";
}
};

class Car : public Vehicle, public FourWheeler


{
public:
Car()
{
cout << "This Four Wheeler Vehicle is a Car\n";
}
};

int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.

Car obj;
return 0;
}

OUTPUT:

This is a Vehicle
This is a Four Wheeler
This Four Wheeler Vehicle is a Car

Dept. of ECE, GSSSIETW, Mysuru Page 38


BEC358C C++ Basics

Experiment 11 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

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.
AIM: To 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.

THEORY:
In C++, the “this” pointer holds the memory address of the
class instance that is being called by a member function,
allowing those functions to correctly access the object’s data
members. It’s not necessary to explicitly define the “this”
pointer as a function argument within the class, as the compiler
handles it automatically. In other words, it is a powerful
concept in object-oriented programming languages that allows objects to refer to themselves within
their own scope. The 'this' pointer in C++ is an implicit pointer available within non-static member
functions of a class or structure. It points to the current object instance, letting the object access its
own member variables and functions.

ALGORITHM:

1. Start.
2. Define the class CountObject:
 Declare private data members:
o roll_no: Integer to store roll number.
o Name: String to store name.
 Define public member functions:
o set_data(int r, const string& n):

Dept. of ECE, GSSSIETW, Mysuru Page 39


BEC358C C++ Basics

 Assign r to roll_no.
 Assign n to Name.
o display():
 Print the memory address of the object using this.
 Print the values of roll_no and Name.
3. In the main function
 Declare three objects of CountObject: obj1, obj2, obj3.
 Call set_data() for each object:

 For obj1, pass roll number 1 and name "Sita".


 For obj2, pass roll number 2 and name "Gita".
 For obj3, pass roll number 3 and name "Rita".

 Call display() for each object:


 Display the memory address, roll number, and name for obj1.
 Display the memory address, roll number, and name for obj2.
 Display the memory address, roll number, and name for obj3.
4. End.

PROGRAM:

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

class CountObject
{
private:
int roll_no;
string Name;

public:

// Member function to set data values

Dept. of ECE, GSSSIETW, Mysuru Page 40


BEC358C C++ Basics

void set_data(int r, const string n)


{
roll_no = r;
Name = n;
}

// Member function to display data and identify invoking object


void display()
{
cout << "Object invoked at address: " << this << endl;
cout << "Roll Number: " << roll_no << endl;
cout << "Name: " << Name << endl;
}
};

int main()
{
// Creating three objects
CountObject obj1, obj2, obj3;

// Setting data for each object


obj1.set_data(1, "Alice");
obj2.set_data(2, "Bob");
obj3.set_data(3, "Charlie");

// Displaying data for each object


cout << "Details of Object 1:" << endl;
obj1.display();
cout << "\nDetails of Object 2:" << endl;
obj2.display();
cout << "\nDetails of Object 3:" << endl;
Dept. of ECE, GSSSIETW, Mysuru Page 41
BEC358C C++ Basics

obj3.display();
return 0;
}

OUTPUT:

Details of Object 1:
Object invoked at address: 0x7ffd240ef770
Roll Number: 1
Name: Alice

Details of Object 2:
Object invoked at address: 0x7ffd240ef740
Roll Number: 2
Name: Bob

Details of Object 3:
Object invoked at address: 0x7ffd240ef710
Roll Number: 3
Name: Charlie

Dept. of ECE, GSSSIETW, Mysuru Page 42


BEC358C C++ Basics

Experiment 12 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)

Write a C++ program to implement exception handling with minimum 5


exceptions classes including two built in exceptions.
AIM: To Write a C++ program to implement exception handling with minimum 5 exceptions classes
including two built in exceptions.

THEORY:
An exception is an unexpected problem that arises during the execution of a program our program
terminates suddenly with some errors/issues. Exception occurs during the running of the program
(runtime). There are two types of exceptions in C++
1. Synchronous: Exceptions that happen when something goes wrong because of a mistake in the
input data or when the program is not equipped to handle the current type of data it’s working
with, such as dividing a number by zero.
2. Asynchronous: Exceptions that are beyond the program’s control, such as disc failure, keyboard
interrupts, etc.

C++ provides an inbuilt feature for Exception Handling. It can be done using the following specialized
keywords: try, catch, and throw with each having a different purpose.
 throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
 catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an
exception.
 try − A try block identifies a block of code for which particular exceptions will be activated.
It's followed by one or more catch blocks.

ALGORITHM:

1. Start.
2. Define custom exception classes:

Dept. of ECE, GSSSIETW, Mysuru Page 43


BEC358C C++ Basics

o DivideByZeroException: Handles division by zero.


o NegativeNumberException: Handles negative numbers for square root.
o InvalidOperationException: Handles unsupported operations.
3. Include built-in exception classes:
o std::out_of_range: Handles inputs that are too large.
o std::invalid_argument: Handles invalid arguments during subtraction.
4. Define the performOperation function:
o Input: Two integers (a, b) and a string representing the operation (operation).
o Check the operation:
 If the operation is "divide":
 If b == 0, throw DivideByZeroException.
 Otherwise, perform a / b and display the result.
 If the operation is "square_root":
 If a < 0, throw NegativeNumberException.
 Otherwise, compute sqrt(a) and display the result.
 If the operation is "add":
 If a > 1000 or b > 1000, throw std::out_of_range.
 Otherwise, perform a + b and display the result.
 If the operation is "subtract":
 If b > a, throw std::invalid_argument.
 Otherwise, perform a - b and display the result.
 If the operation is not recognized, throw InvalidOperationException.
o Catch exceptions:
 Catch DivideByZeroException and display an error message.
 Catch NegativeNumberException and display an error message.
 Catch std::out_of_range and display the associated error message.
 Catch std::invalid_argument and display the associated error message.
 Catch InvalidOperationException and display an error message.
5. Define the main function:
o Call performOperation with different test cases to verify exception handling:
 Division by zero.
 Square root of a negative number.
 Addition of overly large numbers.
 Subtraction with invalid arguments.
 Unsupported operations.
Dept. of ECE, GSSSIETW, Mysuru Page 44
BEC358C C++ Basics

6. Output:
o For valid operations: Display the result.
o For invalid operations or errors: Display appropriate error messages.
7. End.

PROGRAM:

#include <iostream>
#include <stdexcept>
#include <string>
#include <cmath>

// Custom exception classes


class DivideByZeroException : public std::exception {
public:
const char* what() const noexcept override {
return "Error: Division by zero is not allowed.";
}
};

class NegativeNumberException : public std::exception {


public:
const char* what() const noexcept override {
return "Error: Negative numbers are not allowed.";
}
};

class InvalidOperationException : public std::exception {


public:
const char* what() const noexcept override {
return "Error: Invalid operation.";
}
};

Dept. of ECE, GSSSIETW, Mysuru Page 45


BEC358C C++ Basics

// Function to demonstrate exception handling


void performOperation(int a, int b, const std::string& operation) {
try {
if (operation == "divide") {
if (b == 0) throw DivideByZeroException();
std::cout << "Result: " << a / b << std::endl;
} else if (operation == "square_root") {
if (a < 0) throw NegativeNumberException();
std::cout << "Result: " << sqrt(a) << std::endl;
} else if (operation == "add") {
if (a > 1000 || b > 1000) throw std::out_of_range("Values are too large.");
std::cout << "Result: " << a + b << std::endl;
} else if (operation == "subtract") {
if (b > a) throw std::invalid_argument("Cannot subtract a larger number from a smaller one.");
std::cout << "Result: " << a - b << std::endl;
} else {
throw InvalidOperationException();
}
} catch (const DivideByZeroException& e) {
std::cerr << e.what() << std::endl;
} catch (const NegativeNumberException& e) {
std::cerr << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cerr << "Out of range error: " << e.what() << std::endl;
} catch (const std::invalid_argument& e) {
std::cerr << "Invalid argument error: " << e.what() << std::endl;
} catch (const InvalidOperationException& e) {
std::cerr << e.what() << std::endl;
}
}

Dept. of ECE, GSSSIETW, Mysuru Page 46


BEC358C C++ Basics

int main() {
// Test the function with different cases
performOperation(10, 0, "divide");
performOperation(-5, 0, "square_root");
performOperation(500, 600, "add");
performOperation(5, 10, "subtract");
performOperation(10, 5, "multiply");

return 0;
}

OUTPUT:

ERROR!
Error: Division by zero is not allowed.
Error: Negative numbers are not allowed.
ERROR!
Result: 1100
Invalid argument error: Cannot subtract a larger number from a smaller one.
Error: Invalid operation.

Dept. of ECE, GSSSIETW, Mysuru Page 47

You might also like