C++ LAB MANUAL (2)
C++ LAB MANUAL (2)
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)
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
return c;
}
OUTPUT:
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).
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);
}
OUTPUT:
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.
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;
{
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:
90
89
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:
ALGORITHM:
1. Start
2. Define the MATRIX class:
• Include a private two-dimensional array to store matrix elements.
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;
}
return temp;
}
/* main function */
int main()
{
matrix m1,m2,m3,m4;
m1.getdata();
m2.getdata();
if(m1==m2)
{
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
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
Experiment 5 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)
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
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
First name
Dob
Surname
Bank balance
5. End
PROGRAM:
#include<iostream>
using namespace std;
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";
}
};
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:
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
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);
};
int main()
{
float fatherIncome, sonIncome;
// Input incomes
FATHER father(fatherIncome);
SON son(sonIncome);
// Calculate and display total income using the friend function
OUTPUT:
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
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;
}
OUTPUT:
Experiment 8 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)
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
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;
height = h;
}
int main() {
// Create pointers to the base class
Polygon *polygonPtr;
return 0;
}
OUTPUT:
Area of Rectangle: 96
Area of Triangle: 72
Experiment 9 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)
THEORY:
ALGORITHM:
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.
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;
}
void calculateNetSalary()
{
allAllowances = static_cast<int>(basicSalary * 1.23);
int grossSalary = basicSalary + allAllowances;
int incomeTax = static_cast<int>(grossSalary * 0.30);
netSalary = grossSalary - incomeTax;
}
{
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:
Employee Details:
Employee Number: 7894
Employee Name: E
Basic Salary: 58746
All Allowances: 72257
Net Salary: 91703
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:
PROGRAM:
#include <iostream>
using namespace std;
//Base class 1
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
// Base class 2
class FourWheeler
{
public:
FourWheeler()
{
cout << "This is a Four Wheeler\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
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):
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:
PROGRAM:
#include <iostream>
#include <string>
using namespace std;
class CountObject
{
private:
int roll_no;
string Name;
public:
int main()
{
// Creating three objects
CountObject obj1, obj2, obj3;
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
Experiment 12 Name :
USN :
Conduction (15M) Write-up (10M) Viva Voce (5M) Total (30M)
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:
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>
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.