Basics C++ Lab
Basics C++ Lab
1.
using inline functions MAX & Min.
Write a C++ program to calculate the volume of different geometric shapes like cube,
2.
cylinder and sphere using function overloading concept.
Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare
3. 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.
Write a C++ program to create class called MATRIX using two-dimensional array of
integers, by overloading the operator == which checks the compatibility of two
4.
matrices to be added and subtracted. Perform the addition and subtraction by
overloading + and – operators respectively. Display the results by overloading the
operator <
Demonstrate simple inheritance concept by creating a base class FATHER with data
members: First Name, Surname, DOB & bank Balance and creating a derived class
5. 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.
Write a C++ program to define class name FATHER & SON that holds the income
6. respectively.
Calculate & display total income of a family using Friend function.
Write a C++ program to accept the student detail such as name & 3 different marks by
7. 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().
Write a C++ program to explain virtual function (Polymorphism) by creating a base
8. 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.
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
9. (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).
Write a C++ program with different class related through multiple inheritance &
10.
demonstrate the use of different access specified by means of members variables &
members functions.
Write a C++ program to create three objects for a class named count object with data
members @#12102023 such as roll_no & Name. Create a members function set_data
11.
( ) for setting the data values & display ( ) member function to display which object
has invoked it using „this‟ pointer.
Write a C++ program to implement exception handling with minimum 5 exceptions
12.
classes including two built in exceptions.
1. Write a C++ program to find largest, smallest & second largest of three numbers using inline
functions MAX & Min.
#include <iostream.h>
#include <conio.h>
// Inline function to find the maximum of two numbers inline int
max(int a, int b) {
return (a > b) ? a : b;
}
// Inline function to find the minimum of two numbers inline int
min(int a, int b) {
return (a < b) ? a : b;
}
void findLargestSmallestSecondLargest(int a, int b, int c, int &largest, int &smallest, int
&secondLargest) {
// Determine the largest largest =
max(max(a, b), c);
// Determine the smallest smallest =
min(min(a, b), c);
// Determine the second largest
if ((a < largest && a > smallest) || (b < largest && b > smallest) || (c < largest && c > smallest))
{
if (a != largest && a != smallest) {
secondLargest = a;
} else if (b != largest && b != smallest) {
secondLargest = b;
} else { secondLargest = c;
}
} else {
secondLargest = smallest; // Default if all numbers are the same
}
}
int main() { clrscr();
int a, b, c;
int largest, smallest, secondLargest;
// Input three numbers
cout << "Enter three numbers: "; cin >>
a >> b >> c;
// Find largest, smallest and second largest findLargestSmallestSecondLargest(a,
b, c, largest, smallest, secondLargest);
// Display results
cout << "Largest number: " << largest << endl; cout <<
"Smallest number: " << smallest << endl;
cout << "Second largest number: " << secondLargest << endl;
getch();
return 0;
}
2. Write a C++ program to calculate the volume of different geometric shapes like cube,
cylinder and sphere using function overloading concept.
#include <iostream.h>
#include <conio.h>
// Function to calculate the volume of a cube inline
double volume(double side) {
return side * side * side;
}
// Function to calculate the volume of a cylinder inline
double volume(double radius, double height) {
return 3.14159 * radius * radius * height;
}
// Function to calculate the volume of a sphere inline
double volume(double radius) {
return (4.0 / 3.0) * 3.14159 * radius * radius * radius;
}
void main() {
clrscr(); // Clear the screen double
side, radius, height;
// Calculate and display the volume of a cube cout <<
"Enter the side length of the cube: "; cin >> side;
cout << "Volume of the cube: " << volume(side) << endl;
// Calculate and display the volume of a cylinder
cout << "Enter the radius and height of the cylinder: "; cin >>
radius >> height;
cout << "Volume of the cylinder: " << volume(radius, height) << endl;
// Calculate and display the volume of a sphere cout <<
"Enter the radius of the sphere: ";
cin >> radius;
cout << "Volume of the sphere: " << volume(radius) << endl;
getch(); // Wait for a key press
}
3. Define a STUDENT class with USN, Name & Marks in 3 tests of a subject. Declare
an array of 10 STUDENT objects. Using appropriate functions, find the average of
the two better marks for each student. Print the USN, Name & the average marks of
all the students.
#include
<iostream.h>
#include <conio.h>
class STUDENT {
char usn[15];
char
name[50];
float
marks[3];
public:
// Function to input data for a
student void input() {
cout << "Enter USN:
"; cin >> usn;
cout << "Enter Name: ";
cin.ignore(); // Ignore newline character from previous
input cin.getline(name, 50);
cout << "Enter marks for 3 tests: ";
cin >> marks[0] >> marks[1] >> marks[2];
}
// Function to calculate the average of the two best marks
float averageOfBestTwo() const {
float first, second,
third; first = marks[0];
second =
marks[1]; third =
marks[2];
// Find the two highest
marks if (first < second) {
swap(first, second);
}
if (first < third) {
swap(first,
third);
}
if (second < third) {
swap(second,
third);
}
// Now first and second are the highest two
marks return (first + second) / 2.0;
}
// Function to display student
details void display() const {
cout << "USN: " << usn <<
endl; cout << "Name: " << name
<< endl;
cout << "Average of best two marks: " << averageOfBestTwo() << endl;
}
};
void main() {
clrscr(); // Clear the
screen STUDENT
students[10];
int i;
// Input data for 10
students for (i = 0; i < 10;
++i) {
cout << "\nEnter details for student " << (i + 1) << ":" <<
endl; students[i].input();
}
// Display data for all
students cout << "\nStudent
details:\n"; for (i = 0; i < 10;
++i) {
students[i].display();
cout << "-----------------------\n";
}
getch(); // Wait for a key press
}
4. Write a C++ program to create class called MATRIX using two-dimensional array of
integers, by
overloading the operator == which checks the compatibility of two matrices to be
added and
subtracted. Perform the addition and subtraction by overloading + and – operators
respectively. Display the results by overloading the operator < < If (m1 == m2) then
m3 = m1 + m2 and m4 = m1 – m2 else display error
#include <iostream.h>
#include <conio.h>
class MATRIX {
int rows, cols;
int data[10][10]; // Adjust size based on your requirements
public:
// Constructor to initialize matrix dimensions and values
MATRIX(int r = 0, int c = 0) : rows(r), cols(c) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = 0;
}
}
}
// Function to input matrix
elements void input() {
cout << "Enter elements for a " << rows << "x" << cols << " matrix:" <<
endl; for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j+
+) { cin >> data[i][j];
}
}
}
// Overloaded == operator to check matrix
compatibility int operator==(const MATRIX& m)
const {
return (rows == m.rows) && (cols == m.cols);
}
// Overloaded + operator to add two
matrices MATRIX operator+(const
MATRIX& m) const {
MATRIX result(rows,
cols); if (*this == m) {
for (int i = 0; i < rows; i+
+) { for (int j = 0; j <
cols; j++) {
result.data[i][j] = data[i][j] + m.data[i][j];
}
}
}
return result;
}
// Overloaded - operator to subtract two
matrices MATRIX operator-(const MATRIX&
m) const {
MATRIX result(rows,
cols); if (*this == m) {
for (int i = 0; i < rows; i+
+) { for (int j = 0; j <
cols; j++) {
result.data[i][j] = data[i][j] - m.data[i][j];
}
}
}
return result;
}
// Overloaded << operator to display matrix
friend ostream& operator<<(ostream& out, const MATRIX&
m) { for (int i = 0; i < m.rows; i++) {
for (int j = 0; j < m.cols; j+
+) { out << m.data[i][j]
<< " ";
}
out << endl;
}
return out;
}
};
void main() {
clrscr(); // Clear the
screen int r1, c1, r2, c2;
// Input for first matrix
cout << "Enter the number of rows and columns for the first matrix:
"; cin >> r1 >> c1;
MATRIX m1(r1, c1);
m1.input();
// Input for second matrix
cout << "Enter the number of rows and columns for the second
matrix: "; cin >> r2 >> c2;
MATRIX m2(r2, c2);
m2.input();
// Check if matrices are
compatible if (m1 == m2) {
MATRIX m3 = m1 + m2; // Matrix
addition MATRIX m4 = m1 - m2; //
Matrix subtraction
// Display results
cout << "\nMatrix m1 + m2:\n" <<
m3; cout << "\nMatrix m1 - m2:\n"
<< m4;
} else {
cout << "\nError: Matrices have different dimensions and cannot be
added or subtracted.";
}
getch(); // Wait for a key press
}
5. Demonstrate simple inheritance concept by creating a base class FATHER with data
members:
First Name, Surname, DOB & bank Balance and creating a derived class SON, which
inherits: Surname & Bank Balance feature from base class but provides its own
feature: First Name & DOB. Create & initialize F1 & S1 objects with appropriate
constructors & display the FATHER & SON details.
#include <iostream.h>
#include <conio.h>
#include <string.h>
// Base class
class FATHER {
protected:
char surname[30];
float bankBalance;
public:
// Constructor for FATHER
FATHER(const char* s, float b) {
strcpy(surname, s);
bankBalance = b;
}
// Function to display FATHER details
void displayFather() const {
cout << "Surname: " << surname << endl;
cout << "Bank Balance: $" << bankBalance << endl;
}
};
// Derived class
class SON : public FATHER {
private:
char firstName[30];
char dob[15]; // Date of Birth in DD/MM/YYYY format
public:
// Constructor for SON
SON(const char* fn, const char* d, const char* s, float b) : FATHER(s, b) {
strcpy(firstName, fn);
strcpy(dob, d);
}
// Function to display SON details
void displaySon() const {
cout << "Date of Birth: " << dob << endl;
// Calling the base class method to display inherited
attributes displayFather();
}
};
void main() {
clrscr(); // Clear the screen
// Create and initialize FATHER
object FATHER F1("Smith",
50000.00);
// Create and initialize SON object
SON S1("John", "01/01/1990", "Smith", 50000.00);
// Display details of FATHER
cout << "FATHER Details:" <<
endl; F1.displayFather();
// Display details of SON
cout << "\nSON Details:" <<
endl; S1.displaySon();
getch( ); // Wait for a key press
6. Write a C++ program to define class name FATHER & SON that holds the income
respectively. Calculate & display total income of a family using Friend function.
#include<iostream.h>
#include <conio.h>
class SON; // Forward
declaration class FATHER {
private:
float
income;
public:
// Constructor to initialize
income FATHER(float inc) :
income(inc) {}
// Friend function declaration
friend void displayTotalIncome(const FATHER&, const SON&);
};
class
SON {
private:
float
income;
public:
// Constructor to initialize
income SON(float inc) :
income(inc) {}
// Friend function declaration
friend void displayTotalIncome(const FATHER&, const SON&);
};
// Friend function definition to calculate and display total
income void displayTotalIncome(const FATHER& f, const
SON& s) {
float totalIncome = f.income + s.income;
cout << "Total income of the family: $" << totalIncome << endl;
}
void main() {
clrscr(); // Clear the screen
// Create and initialize FATHER and SON
objects FATHER father(80000.00); //
Father's income SON son(30000.00); //
Son's income
// Display total family income using the friend
function displayTotalIncome(father, son);
getch(); // Wait for a key press
}
7. Write a C++ program to accept the student detail such as name & 3 different
marks by get_data() method & display the name & average of marks using
display() method. Define a friend function for calculating the average marks using
the method mark_avg().
#include <iostream.h>
#include <conio.h>
#include <string.h>
class STUDENT {
private:
char
name[50];
float
marks[3];
public:
// Method to input student details
void get_data() {
cout << "Enter student name: ";
cin.ignore(); // Clear newline from previous input
cin.getline(name, 50);
cout << "Enter marks for 3 subjects: ";
cin >> marks[0] >> marks[1] >>
marks[2];
}
// Method to display student
details void display() const {
cout << "Name: " << name << endl;
cout << "Average Marks: " << mark_avg(*this) << endl;
}
// Friend function declaration
friend float mark_avg(const STUDENT& s);
};
// Friend function definition to calculate the average of
marks float mark_avg(const STUDENT& s) {
float total = s.marks[0] + s.marks[1] +
s.marks[2]; return total / 3.0;
}
void main() {
clrscr(); // Clear the
screen STUDENT
student;
// Input student details
student.get_data();
// Display student
details
student.display();
getch(); // Wait for a key press
}
10 Write a C++ program with different class related through multiple inheritance &
. demonstrate the use of different access specified by means of members variables &
members functions.
#include <iostream.h>
#include <conio.h>
// Base class
1 class
Person {
protected:
char
name[50]; int
age;
public:
// Function to set the person details
void setPersonDetails(const char* n, int a) {
strcpy(name, n);
age = a;
}
// Function to display person
details void
displayPersonDetails() const {
cout << "Name: " << name <<
endl; cout << "Age: " << age <<
endl;
}
};
// Base class 2
class Employee
{ private:
int
employeeID;
public:
// Function to set the employee
ID void setEmployeeID(int id) {
employeeID = id;
}
// Function to display employee
ID void displayEmployeeID()
const {
cout << "Employee ID: " << employeeID << endl;
}
};
// Derived class
class Manager : public Person, public
Employee { private:
char
department[50];
public:
// Function to set manager details
void setManagerDetails(const char* n, int a, int id, const char*
dept) { setPersonDetails(n, a); // Set details in base class Person
setEmployeeID(id); // Set details in base class Employee
strcpy(department, dept);
}
// Function to display manager
details void
displayManagerDetails() const {
displayPersonDetails(); // Call base class Person function
displayEmployeeID(); // Call base class Employee
function cout << "Department: " << department << endl;
}
};
void main() {
clrscr(); // Clear the screen
// Create an object of
Manager Manager mgr;
// Set manager details
mgr.setManagerDetails("Alice", 35, 1001,
"Sales");
// Display manager details
mgr.displayManagerDetails(
); getch(); // Wait for a key
press
}
11 Write a C++ program to create three objects for a class named count object with data
. members such as roll_no & Name. Create a members function set_data ( ) for setting
the data values & display ( ) member function to display which object has invoked it
using „this‟ pointer.
#include <iostream.h>
#include <conio.h>
class CountObject
{ private:
int roll_no;
char
Name[50];
public:
// Function to set the data values
void set_data(int roll, const char*
name) { roll_no = roll;
strcpy(Name, name);
}
// Function to display the data values and which object invoked it
void display() const {
cout << "Roll No: " << roll_no <<
endl; cout << "Name: " << Name
<< endl;
cout << "This object address: " << this << endl;
}
};
void main() {
clrscr(); // Clear the screen
// Create three objects of
CountObject CountObject obj1,
obj2, obj3;
// Set data for each object
obj1.set_data(101, "Alice");
obj2.set_data(102, "Bob");
obj3.set_data(103,
"Charlie");
// Display data for each object
cout << "Object 1 details:" <<
endl; obj1.display();
cout << endl;
cout << "Object 2 details:" <<
endl; obj2.display();
cout << endl;
cout << "Object 3 details:" <<
endl; obj3.display();
#include <iostream.h>
#include <conio.h>
// Custom Exception
Classes class
MyException {
public:
const char* what() const {
return "MyException occurred!";
}
};
class
FileNotFoundException {
public:
const char* what() const {
return "FileNotFoundException: File not found!";
}
};
class
DivisionByZeroException {
public:
const char* what() const {
return "DivisionByZeroException: Division by zero!";
}
};
class
NegativeValueException {
public:
const char* what() const {
return "NegativeValueException: Negative value encountered!";
}
};
class
OutOfRangeException {
public:
OutOfRangeException(const char* msg) : message(msg)
{} const char* what() const {
return message;
}
private:
const char* message;
};
// Function to demonstrate throwing and catching
exceptions void demoFunction(int choice) {
switch (choice)
{ case 1:
throw
MyException(); case
2:
throw
FileNotFoundException(); case
3:
throw
DivisionByZeroException(); case 4:
throw
NegativeValueException(); cas
5:
throw OutOfRangeException("OutOfRangeException: Value out of
range!"); default:
cout << "No exception thrown." <<
endl; break;
}
}
void main() {
clrscr(); // Clear the
screen try {
int choice;
cout << "Enter a choice (1-5) to throw an
exception: "; cin >> choice;
demoFunction(choice);
}
catch (MyException& e) {
cout << "Caught exception: " << e.what() << endl;
}
catch (FileNotFoundException& e) {
cout << "Caught exception: " << e.what() << endl;
}
catch (DivisionByZeroException& e) {
cout << "Caught exception: " << e.what() << endl;
}
catch (NegativeValueException& e) {
cout << "Caught exception: " << e.what() << endl;
}
catch (OutOfRangeException& e) {
cout << "Caught exception: " << e.what() << endl;
}
catch (...) { // Catch all other exceptions
cout << "Caught an unknown exception." << endl;
}
getch(); // Wait for a key press
}