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

C++ Basic Lab Manual

Uploaded by

ANU
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)
271 views

C++ Basic Lab Manual

Uploaded by

ANU
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/ 27

BANGALORE COLLEGE OF ENGINEERING AND TECHNOLOGY

CHANDAPURA, BANGALORE 560099

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

Ability Enhancement Course


BEC358C- C++ BASICS
(REGULATION 2022 SCHEME)

THIRD SEMESTER / ECE

LAB MANUAL
EXPERIMENT-1
AIM: Write a C++ program to find largest, smallest & second
largest of three numbers using inline functions MAX & Min.

PROGRAM
#include <iostream>
using namespace std;
inline int MAX(int a, int b , int c)
{
if(a>=b && a>=c)
return a;
else if(b>=a && 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<=a && b<=c)
return b;
else
return c;
}
int main()
{
int h,k;
int x,y,z; // Variables to store three numbers
cout<<"Enter three numbers:\n";
cin>>x>>y>>z;
h=MAX(x,y,z);
k=Min(x,y,z);
cout<<"largest is: "<<h<<"\nSmallest is: "<<k<<"\n";
if(h==x&&k==y|| h==y&& k==x)
cout<<"Second largest is: "<<z<<"\n";
else if((h==x&&k==z|| h==z&& k==x))
cout<<"Second largest is: "<<y<<"\n";
else
cout<<"Second largest is: "<<x<<"\n";
return 0;
}

EXPECTED OUTPUT:

Enter three numbers:

539

largest is: 9

Smallest is: 3

Second largest is: 5

EXPERIMENT-2

AIM: Write a C++ program to calculate the volume of different


geometric shapes like cube, cylinder and sphere using function
overloading concept.

PROGRAM
#include <iostream>
#include<cmath>
using namespace std;
int volume(int a) // Volume of cube
{
return a*a*a;
}
double volume(int r , int h) // Volume of cylinder
{
return M_PI*r*r*h;
}
double volume(double r_s) // Volume of sphere
{
return 4*M_PI*r_s*r_s*r_s/3;
}
int main()
{
int a,r,h;
double r_s;
cout<<"Enter side lenght of cude:";
cin>>a;
cout<<"\n Volume of cube is:"<<volume(a);
cout<<"\nEnter radius and height of cylinder:";
cin>>h>>r;
cout<<"\n Volume of cylinder is:"<<volume(h,r);
cout<<"\n Enter radius of sphere:";
cin>>r_s;
cout<<"\n Volume of sphere is:"<<volume(r_s);
return 0;
}
EXPECTED OUTPUT
Enter side lenght of cude:2
Volume of cube is:8
Enter radius and height of cylinder:2 3
Volume of cylinder is:37.6991
Enter radius of sphere:4
Volume of sphere is:268.083
EXPERIMENT-3
AIM: 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.

PROGRAM
#include <iostream>
using namespace std;
class STUDENT
{
public:
string USN, Name;
int mark1, mark2, mark3;
void get_details(string usn, string name)
{
USN=usn;
Name=name;
}
void get_marks(int m1, int m2, int m3)
{
mark1=m1;
mark2=m2;
mark3=m3;
}
double average()
{
double avg;
int largest, secondLargest;
if (mark1 >= mark2 && mark1 >= mark3) {
largest = mark1;
secondLargest = (mark2 >= mark3) ? mark2 : mark3;
} else if (mark2 >= mark1 && mark2 >= mark3) {
largest = mark2;
secondLargest = (mark1 >= mark3) ? mark1 : mark3;
} else {
largest = mark3;
secondLargest = (mark1 >= mark2) ? mark1 : mark2;
}
return avg=(largest+secondLargest)/2.0;
}
};
int main()
{
STUDENT student[10];
string usn[10], name[10];
//Student information
for(int i=0;i<10;i++)
{
cout<<"Enter USN of student"<<i+1<<":";
cin>>usn[i];
cout<<"Enter Name of student"<<i+1<<":";
cin>>name[i];
student[i].get_details(usn[i], name[i]);
int m1, m2,m3;
cout<<"Enter Marks of three tests for student"<<i+1<<":";
cin>>m1>>m2>>m3;
student[i].get_marks(m1,m2,m3);
}
cout<<"................Student details.................\n";
for(int i=0;i<10;i++)
{
cout<<"\nUSN of student"<<i+1<<":"<<student[i].USN;
cout<<"\nName of student"<<i+1<<":"<<student[i].Name;
cout<<"\nAverage marks of
student"<<i+1<<":"<<student[i].average();
cout<<"\n*******************************";
}
return 0;
}
EXPECTED OUTPUT:
Enter USN of student1:4KV04EC001
Enter Name of student1:ABHI
Enter Marks of three tests for student1:23 25 25
Enter USN of student2:4KV04EC002
Enter Name of student2:BHASKAR
Enter Marks of three tests for student2:25 15 10
Enter USN of student3:4KV04EC003
Enter Name of student3:CHARAN
Enter Marks of three tests for student3:23 23 23
Enter USN of student4:4KV04EC004
Enter Name of student4:FARUK
Enter Marks of three tests for student4:25 10 19
Enter USN of student5:4KV04EC005
Enter Name of student5:GANU
Enter Marks of three tests for student5:23 21 21
Enter USN of student6:4KV04EC006
Enter Name of student6:SHARUK
Enter Marks of three tests for student6:10 2 3
Enter USN of student7:4KV04EC007
Enter Name of student7:ISHANA
Enter Marks of three tests for student7:23 10 15
Enter USN of student8:4KV04EC008
Enter Name of student8:RAGU
Enter Marks of three tests for student8:2 3 6
Enter USN of student9:4KV04EC009
Enter Name of student9:REETHA
Enter Marks of three tests for student9:23 10 12
Enter USN of student10:4KV04EC010
Enter Name of student10:TARA
Enter Marks of three tests for student10:23 23 23
................Student details.................
USN of student1:4KV04EC001
Name of student1:ABHI
Average marks of student1:25
*******************************
USN of student2:4KV04EC002
Name of student2:BHASKAR
Average marks of student2:20
*******************************
USN of student3:4KV04EC003
Name of student3:CHARAN
Average marks of student3:23
*******************************
USN of student4:4KV04EC004
Name of student4:FARUK
Average marks of student4:22
*******************************
USN of student5:4KV04EC005
Name of student5:GANU
Average marks of student5:22
*******************************
USN of student6:4KV04EC006
Name of student6:SHARUK
Average marks of student6:6.5
*******************************
USN of student7:4KV04EC007
Name of student7:ISHANA
Average marks of student7:19
*******************************
USN of student8:4KV04EC008
Name of student8:RAGU
Average marks of student8:4.5
*******************************
USN of student9:4KV04EC009
Name of student9:REETHA
Average marks of student9:17.5
*******************************
USN of student10:4KV04EC010
Name of student10:TARA
Average marks of student10:23

EXPERIMENT-4

AIM: Write a C++ program to create class called MATRIX using


twodimensional array of integers, by overloading the operator ==
which checks the compatibility of two matrices to be added and
subtracted. Perform the addition and subtraction by overloading +
and – operators respectively. Display the results by overloading the
operator <<. If (m1 == m2) then m3 =m1 + m2 and m4 = m1 – m2
else display error

PROGRAM:
#include <iostream>
using namespace std;
class MATRIX {
public:
int row, col;
int matrix[10][10];
void get_size() {
cin >> row >> col;
}
void get_elements() {
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cin >> matrix[i][j];
}
bool operator ==(const MATRIX& temp) {
return row == temp.row && col == temp.col;
}
MATRIX operator +(const MATRIX& temp) {
MATRIX result;
result.row = row;
result.col = col;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
result.matrix[i][j] = matrix[i][j] + temp.matrix[i][j];
return result;
}
MATRIX operator -(const MATRIX& temp) {
MATRIX result;
result.row = row;
result.col = col;
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
result.matrix[i][j] = matrix[i][j] - temp.matrix[i][j];
return result;
}
friend ostream& operator <<(ostream& os, const MATRIX& temp) {
for (int i = 0; i < temp.row; i++) {
for (int j = 0; j < temp.col; j++)
os << temp.matrix[i][j] << " ";
os << endl;
}
return os;
}
};
int main() {
MATRIX m1, m2, m3, m4;
cout << "Enter number of rows and columns of m1: ";
m1.get_size();
cout << "Enter number of rows and columns of m2: ";
m2.get_size();
if (m1 == m2) {
cout << "Enter elements of m1: ";
m1.get_elements();
cout << "Enter elements of m2: ";
m2.get_elements();
m3 = m1 + m2;
m4 = m1 - m2;
cout << "Matrix 1 + Matrix 2:\n" << m3;
cout << "Matrix 1 - Matrix 2:\n" << m4;
}
else {
cout << "Error: Matrices are not compatible for
addition/subtraction." << endl;
}
return 0;
}
EXPECTED OUTPUT:
CASE-I:
Enter number of rows and columns of m1: 2 3
Enter number of rows and columns of m2: 2 3
Enter elements of m1: 1 2 3 4 5 6
Enter elements of m2: 3 1 7 4 8 2
Matrix 1 + Matrix 2:
4 3 10
8 13 8
Matrix 1 - Matrix 2:
-2 1 -4
0 -3 4
CASE-II:
Enter number of rows and columns of m1: 2 3
Enter number of rows and columns of m2: 3 2
Error: Matrices are not compatible for addition/subtraction.

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

PROGRAM

#include <iostream>
using namespace std;
class FATHER
{
protected:
string First_name, Surname, DOB;
public:
double Bank_balance;
public:
FATHER(string first_name, string surname, string dob, double
bank_balance)
: First_name(first_name), Surname(surname), DOB(dob),
Bank_balance(bank_balance) {}
void display()
{
cout << "----------Father Details---------" << endl;
cout << "First Name: " << First_name << endl;
cout << "Surname: " << Surname << endl;
cout << "DOB: " << DOB << endl;
cout << "Bank Balance: " << Bank_balance << endl;
}
};
class SON : public FATHER
{
public:
SON(string first_name, string surname, string dob, double
bank_balance)
: FATHER(first_name, surname, dob, bank_balance) {}
void display()
{
cout << "----------Son Details---------" << endl;
cout << "First Name: " << First_name << endl;
cout << "Surname: " << Surname << endl;
cout << "DOB: " << DOB << endl;
cout << "Bank Balance: " << Bank_balance << endl;
}
};
int main() {
FATHER F1("XYZ ", "ABC", "1986-06-14", 100000.0);
F1.display();
SON S1("xyz", "ABC", "1987-01-14", 50000.0);
S1.display();
cout<<"Total bank balance of
SON:"<<F1.Bank_balance+S1.Bank_balance;
return 0;
}
EXPECTED OUTPUT:
----------Father Details---------
First Name: XYZ
Surname: ABC
DOB: 1986-06-14
Bank Balance: 100000
----------Son Details---------
First Name: xyz
Surname: ABC
DOB: 1987-01-14
Bank Balance: 50000
Total bank balance of SON:150000

EXPERIMENT-6

AIM: Write a C++ program to define class name FATHER & SON
that holds the income respectively. Calculate & display total income
of a family using friend function.

PROGRAM
#include <iostream>
using namespace std;
// Forward declaration of class Son
class Son;
// Class Father
class Father {
private:
int income;
public:
Father(int inc)
{
income=inc;
}
// Declare friend function to access private member of class Son
friend int calculateTotalIncome(Father f, Son s);
};
// Class Son
class Son {
private:
int income;
public:
Son(int inc)
{
income=inc;
}
// Declare friend function to access private member of class Father
friend int calculateTotalIncome(Father f, Son s);
};
// Friend function to calculate total income
int calculateTotalIncome(Father f, Son s)
{
return f.income + s.income;
}
int main() {
int fatherIncome, sonIncome;
cout << "Enter Father's income: ";
cin >> fatherIncome;
cout << "Enter Son's income: ";
cin >> sonIncome;
Father father(fatherIncome);
Son son(sonIncome);
int totalIncome = calculateTotalIncome(father, son);
cout << "Total family income: " << totalIncome << endl;
return 0;
}
EXPECTED OUTPUT:
Enter Father's income: 10500
Enter Son's income: 10000
Total family income: 20500
EXPERIMENT-7
AIM: Write a C++ program to accept the student detail such as
name & 3 different marks by get_data() method & display the name
& average of marks using display() method. Define a friend function
for calculating the average marks using the method mark_avg().

PROGRAM
#include <iostream>
using namespace std;
class Student; // Forward declaration for friend function
class Student {
private:
string name;
int mark1, mark2, mark3;
public:
// Method to accept student details
void get_data() {
cout << "Enter student name: ";
cin>>name;
cout << "Enter three marks: ";
cin >> mark1 >> mark2 >> mark3;
}
// Friend function to calculate average marks
friend float mark_avg( Student student);
// Method to display student name and average marks
void display() {
float avg = mark_avg(*this);
cout << "Student Name: " << name << endl;
cout << "Average Marks: " << avg << endl;
}
};
// Friend function to calculate average marks
float mark_avg(Student student) {
return (student.mark1 + student.mark2 + student.mark3) / 3.0;
}
int main() {
Student student;
student.get_data();
student.display();
return 0;
}

EXPECTED OUTPUT:
Enter student name: AKAKANKSH
Enter three marks: 10 12 15
Student Name: AKAKANKSH
Average Marks: 12.3333

EXPERIMENT-8
AIM: Write a C++ program to explain virtual function
(Polymorphism) by creating a base class polygon which has virtual
function areas two classes rectangle & triangle derived from
polygon & they have area to calculate & return the area of rectangle
& triangle respectively.

PROGRAM
#include <iostream>
using namespace std;
class Polygon {
public:
// Virtual function to calculate the area of the polygon
virtual float area() {
return 0.0;
}
};
class Rectangle : public Polygon {
private:
float length, breadth;
public:
Rectangle(float l, float b)
{
length=l;
breadth=b;
}
// Override the area() function for Rectangle
float area() {
return length * breadth;
}
};
class Triangle : public Polygon {
private:
float base, height;
public:
Triangle(float b, float h)
{
base=b;
height=h;
}
// Override the area() function for Triangle
float area() {
return 0.5 * base * height;
}
};
int main() {
Polygon* shapes[2];
Rectangle rect(5, 10);
Triangle tri(4, 6);
shapes[0] = &rect;
shapes[1] = &tri;
for (int i = 0; i < 2; ++i) {
cout << "Area of shape " << i + 1 << ": " << shapes[i]->area() <<
endl;
}
return 0;
}
EXPECTED OUTPUT:
Area of shape 1: 50
Area of shape 2: 12

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

PROGRAM
#include <iostream>
using namespace std;
class EMPLOYEE {
private:
int employeeNumber;
string employeeName;
int basicSalary;
int allAllowances;
int netSalary;
public:
// Function to read employee data
void readData() {
cout << "Enter Employee Number: ";
cin >> employeeNumber;
cout << "Enter Employee Name: ";
// cin.ignore();
//getline(cin, employeeName);
cin>>employeeName;
cout << "Enter Basic Salary: ";
cin >> basicSalary;
}
// Function to calculate net salary
void calculateNetSalary() {
allAllowances = 1.23 * basicSalary;
int grossSalary = basicSalary + allAllowances;
int incomeTax = 0.3 * grossSalary;
netSalary = grossSalary - incomeTax;
}
// Function to print employee details
void printData() {
cout << "\nEmployee Number: " << employeeNumber << endl;
cout << "Employee Name: " << employeeName << endl;
cout << "Basic Salary: " << basicSalary << endl;
cout << "All Allowances: " << allAllowances << endl;
cout << "Net Salary: " << netSalary << endl;
}
};
int main() {
EMPLOYEE emp;
emp.readData();
emp.calculateNetSalary();
emp.printData();
return 0;
}
EXPECTED OUTPUT:
Enter Employee Number: 12001
Enter Employee Name: STEVE
Enter Basic Salary: 25000
Employee Number: 12001
Employee Name: STEVE
Basic Salary: 25000
All Allowances: 30750
Net Salary: 39025
EXPERIMENT-10
AIM: Write a C++ program with different class related through
multiple inheritance & demonstrate the use of different access
specifier by means of members variables & members functions.

PROGRAM
#include <iostream>
using namespace std;
// Base class: Person
class Person {
protected:
string name;
int age;
public:
// Public member function to set person details
void setPersonDetails(string n, int a) {
name = n;
age = a;
}
// Public member function to display person details
void displayPersonDetails() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Base class: Address
class Address {
protected:
string city;
string country;
public:
// Public member function to set address details
void setAddressDetails(string c, string cn) {
city = c;
country = cn;
}
// Public member function to display address details
void displayAddressDetails() {
cout << "City: " << city << ", Country: " << country << endl;
}
};
// Derived class: Employee (Multiple Inheritance from Person and
Address)
class Employee : public Person, public Address {
private:
double salary;
public:
// Public member function to set employee details
void setEmployeeDetails(double s) {
salary = s;
}
// Public member function to display employee details
void displayEmployeeDetails() {
cout << "Employee Details:" << endl;
displayPersonDetails(); // Accessing the member function from the
Person class
displayAddressDetails(); // Accessing the member function from the
Address class
cout << "Salary: $" << salary << endl;
}
};
int main() {
Employee emp;
// Setting person details for employee
emp.setPersonDetails("Akakanksh K", 30);
emp.setAddressDetails("New York", "USA");
emp.setEmployeeDetails(50000);
// Displaying employee details
emp.displayEmployeeDetails();
return 0;
}
EXPECTED OUTPUT:
Employee Details:
Name: Akakanksh K, Age: 30
City: New York, Country: USA
Salary: $50000

EXPERIMENT-11

AIM: Write a C++ program to create three objects for a class


named count object with data members such as roll_no & Name.
Create a members function set_data ( ) for setting the data values &
display ( ) member function to display which object has invoked it
using “this” pointer.

PROGRAM
#include <iostream>
using namespace std;
class CountObject {
private:
int roll_no;
string name;
public:
// Member function to set data values
void set_data(int roll, string nm) {
this->roll_no = roll;
this->name = nm;
}
// Member function to display which object has invoked it using "this"
pointer
void display() {
cout << "Object with Roll No: " << this->roll_no << ", Name: " << this-
>name;
cout << " has invoked the display() function using this pointer." <<
endl;
}
};
int main() {
CountObject obj1, obj2, obj3;
obj1.set_data(101, "Alice");
obj2.set_data(102, "Bob");
obj3.set_data(103, "Charlie");
obj1.display();
obj2.display();
obj3.display();
return 0;
}
EXPECTED OUTPUT:
Object with Roll No: 101, Name: Alice has invoked the display()
function using this pointer.
Object with Roll No: 102, Name: Bob has invoked the display()
function using this pointer.
Object with Roll No: 103, Name: Charlie has invoked the display()
function using this pointer.
EXPERIMENT-12
AIM: Write a C++ program to implement exception handling with
minimum 5 exceptions classes including two built in exceptions.

PROGRAM
#include <iostream>
#include <string>
using namespace std;
// Custom exception classes
class DivisionByZeroException : public exception {
public:
const char* what() const throw() {
return "Division by zero is not allowed.";
}
};
class NegativeNumberException : public exception {
public:
const char* what() const throw() {
return "Negative number is not allowed.";
}
};
// Function to divide two numbers
double divideNumbers(double num1, double num2) {
if (num2 == 0) {
throw DivisionByZeroException();
}
return num1 / num2;
}
int main() {
try {
// Example 1: Division by zero
double result = divideNumbers(10, 0);
cout << "Result: " << result << endl;
// Example 2: Negative number
double number = -5;
if (number < 0) {
throw NegativeNumberException();
}
cout << "Number: " << number << endl;
}
catch (const DivisionByZeroException& ex) {
cerr << "Caught DivisionByZeroException: " << ex.what() << endl;
}
catch (const NegativeNumberException& ex) {
cerr << "Caught NegativeNumberException: " << ex.what() << endl;
}
catch (const exception& ex) {
cerr << "Caught an exception: " << ex.what() << endl;
}
catch (...) {
cerr << "Caught an unknown exception." << endl;
}
return 0;
}
EXPECTED OUTPUT:
Caught DivisionByZeroException: Division by zero is not allowed.

You might also like