EXPERIMENT-1 (24)
EXPERIMENT-1 (24)
AIM - Write a C++ program to print your personal details by taking input from the user.
THEORY -
In C++, a class serves as a foundational template for creating objects that contain both data
(attributes) and functionality (methods). The UserData class exemplifies this by encapsulating
personal details with controlled access.
By using access specifiers like private and public, the class defines clear boundaries for
visibility: private members such as name and age remain accessible only within the class,
safeguarding internal data, while public members permit external interaction.
The setData method allows secure assignment of values to attributes, and getData retrieves
and displays these values. This approach exemplifies encapsulation by concealing the class’s
internal structure, promoting data integrity and controlled interaction with its contents.
ALGORITHM
2. Define a class PersonalDetails with private data members name and age.
4. Print "Enter your name: " and read the input from the user into name.
5. Print "Enter your age: " and read the input from the user into age.
10. Call the setData() function for object pd to read and store the user’s name and age.
11. Call the getData() function for object pd to print the user’s name and age.
CODE-
#include <iostream>
class PersonalData {
private:
int age;
string name;
public:
void setData() {
};
int main() {
PersonalData user;
user.setData();
user.getData();
return 0;
Output
Experiment-2
AIM - WAP to return the absolute value of variable types integer and float using function
overloading.
THEORY - Function overloading is a feature in C++ that permits multiple functions within the
same scope to share the same name while differing in their parameters. This capability allows
for the use of identical function names for various data types or different numbers of
parameters, thereby enhancing the flexibility and readability of the code.
ALGORITHM
1. It defines two overloaded functions named absolute. One takes an integer as an argument,
and the other takes a float as an argument. These functions calculate the absolute value of
their respective input types and return the result.
2. In the main function, two variables are declared: int a with a value of -5 and float b with a
value of 5.5.
3. The program then calls the absolute function for both a and b and displays the absolute
values using cout.
4. Finally, the program uses the system("pause") function to pause the console window so
that the output can be viewed before the program exits, and it returns 0 to indicate
successful execution.
CODE-
#include <iostream>
int absolute(int);
float absolute(float);
int main() {
int a = -5;
float b = 5.5;
cout<<"Absolute value of "<<a<<" = "<<absolute(a)<<endl;
system("pause");
return 0;
if (var < 0)
var = -var;
return var;
var = -var;
return var;
Output
Experiment-3
AIM - Create a class "employee" that has "Empnumber" and "Enpname" as data members and
member functions getdata() to input data and display() to output data. Writea main function
to create an array of "employee" objects. Accept and print the details of at least 6 employees.
THEORY - In this program, the "Employee" class serves as a prototype for creating employee
objects. Each instance of this class encapsulates both data (attributes) and behavior
(methods) related to employees. This encapsulation ensures that data members, such as
Empnumber and Empname, are integrated with methods like getData and display, thereby
enhancing data integrity and security.
Objects, which are instances of a class, represent real-world entities. In this context, objects
of the "Employee" class symbolize individual employees, and their data is managed through
the defined member functions. These functions are specific to the class and enable
encapsulated behavior. Specifically, the "getData" method is utilized to input employee
information, while the "display" method showcases employee details.
ALGORITHM
1. Define a class Employee with private data members Empnumber and Empname.
2. Implement member functions getdata() to input employee data and display() to output
employee data.
3. In the main function, create an array of Employee objects to store the details of at least 6
employees.
CODE -
#include <iostream>
#include <string>
class Employee {
public:
int Empnumber;
std::string Empname;
void getdata() {
std::getline(std::cin, Empname);
void display() {
};
int main() {
Employee employees[num_employees];
employees[i].getdata();
employees[i].display();
}
return 0;
Output
Experiment-4
AIM - Write a C++ Program to swap two numbers by both call by value and call by reference
mechanism.
Theory - Call by value and call by reference are fundamental techniques in programming for
passing arguments to functions. Call by value involves creating copies of the provided values,
ensuring that any modifications made within the function do not affect the original data. In
contrast, call by reference utilizes references or pointers to the actual variables, enabling
direct modifications to the original data.
ALGORITHM
1. Define a function ‘swapByValue’ that takes two integer parameters, ‘a’ and ‘b’.
2. Inside the function, create a temporary variable ‘temp’ to store the value of ‘a’.
3. Swap the values of ‘a’ and ‘b’ using the temporary variable.
4. The numbers are swapped within the function, but the original values in the ‘main’ function
remain unchanged.
1. Define a function ‘swapByReference’ that takes two integer references, ‘a’ and ‘b’.
2. Inside the function, create a temporary variable ‘temp’ to store the value of ‘a’.
3. Swap the values of ‘a’ and ‘b’ using the temporary variable.
4. The numbers are swapped within the function, and the changes are reflected in the
original variables in the ‘main’ function.
CODE –
#include <iostream>
int temp = a;
a = b;
b = temp;
std::cout << "Inside swapByValue function: a = " << a << ", b = " << b << std::endl;
int temp = a;
a = b;
b = temp;
std::cout << "Inside swapByReference function: a = " << a << ", b = " << b << std::endl;
int main() {
// Swap by value
swapByValue(num1, num2);
std::cout << "After swapByValue function: num1 = " << num1 << ", num2 = " << num2 <<
std::endl;
// Swap by reference
swapByReference(num1, num2);
std::cout << "After swapByReference function: num1 = " << num1 << ", num2 = " << num2 <<
std::endl;
return 0;
}
Output
Experiment-5
AIM- Write a C++ Program to create a simple banking system in which the initial balance and
the rate of interest are read from the keybound and these values are initialised using
constructors.
Theory - Constructors are specialized member functions in C++ that are automatically
invoked when an object is instantiated. Their primary function is to initialize the object's data
members. In the given program, the BankAccount class includes a constructor that accepts
parameters for the initial balance and interest rate. When an object of this class is created,
the constructor is automatically called to set the initial values for its data members.
Constructors are essential for ensuring that objects are in a valid state upon creation,
thereby streamlining the process of object initialization and configuration.
ALGORITHM
1. Define a class BankAccount with private member variables: accountHolder, balance, and
interestRate.
2. Create a constructor for the BankAccount class to initialize the account with a name, initial
balance, and interest rate.
deposit: Allows the user to deposit money into the account. Checks if the amount is
positive.
withdraw: Allows the user to withdraw money from the account. Checks if the amount is
positive and doesn't exceed the current balance.
calculateInterest: Calculates and adds interest to the account balance based on the
given interest rate.
displayAccount: Displays the account holder's name, current balance, and interest rate.
Declare variables name, initialBalance, and rate to store the user's input for the account
holder's name, initial balance, and interest rate.
5. Prompt the user to enter the account holder's name, initial balance, and interest rate using
std::cin.
6. Create a BankAccount object named account using the constructor, passing the user's
input as arguments.
Display a menu with options for deposit, withdrawal, interest calculation, account
details, and exit.
Prompt the user for their choice.
Use a switch statement to handle each menu option:
For deposit, get the deposit amount from the user and call the deposit method. For
withdrawal, get the withdrawal amount from the user and call the withdraw method.
For interest calculation, call the calculateInterest method.
For displaying account details, call the displayAccount method.
For exit, display a goodbye message and exit the program.
8. Repeat the menu loop until the user chooses to exit (e.g., when choice is 5).
CODE-
#include <iostream>
#include <string>
class BankAccount {
private:
std::string accountHolder;
double balance;
double interestRate;
public:
// Constructor to initialize account with a name, initial balance, and interest rate
accountHolder = name;
balance = initialBalance;
interestRate = rate;
if (amount > 0) {
balance += amount;
std::cout << "Deposited $" << amount << " into the account." << std::endl;
} else {
}
// Function to withdraw money from the account
balance -= amount;
std::cout << "Withdrawn $" << amount << " from the account." << std::endl;
} else {
void calculateInterest() {
balance += interest;
void displayAccount() {
std::cout << "Interest Rate: " << interestRate << "%" << std::endl;
};
int main() {
std::string name;
int choice;
do {
switch (choice) {
case 1:
double depositAmount;
account.deposit(depositAmount);
break;
case 2:
double withdrawAmount;
std::cout << "Enter the withdrawal amount: $";
account.withdraw(withdrawAmount);
break;
case 3:
account.calculateInterest();
break;
case 4:
account.displayAccount();
break;
case 5:
break;
default:
std::cout << "Invalid choice. Please select a valid option." << std::endl;
return 0;
Output
Experiment-6
AIM - Write a program to accept five different numbers by creating a class called
friendfunc1and friendfunc2 and calculate the average of these numbers by passing object of
the class to friend function.
Theory -In C++, friend functions represent distinct non-member functions that are explicitly
granted access to a class's private and protected members. In the provided program, the
function calculate Average is declared as a friend of the FriendFunc1 class, which allows it to
access the private data members of FriendFunc1. This arrangement is advantageous when a
function needs to interact with multiple classes or requires access to private members for
specific operations without violating the principles of encapsulation. Friend functions are
particularly effective in fostering collaboration between classes while ensuring data security.
ALGORITHM
. 2. In class friendfunc1, declare an array of integers num to store the five numbers.
3. Define a constructor for class friendfunc1 that accepts five integers as parameters
andstores them in the num array.
5. In class friendfunc2, define the function calculateAverage. This function accepts anobject
of class friendfunc1 as parameter.
6. Inside the calculateAverage function, calculate the sum of the numbers stored in the
numarray of the passed object. Then calculate the average by dividing the sum by 5.
7. In the main function, create an object of class friendfunc1 and initialize it with fivenumbers.
Then create an object of class friendfunc2.
8. Call the calculateAverage function on the object of class friendfunc2, passing the objectof
class friendfunc1 as argument.
CODE-
#include<iostream>
class friendfunc1 {
public:
int num[5];
num[1] = b;
num[2] = c;
num[3] = d;
num[4] = e;
};
};
int main() {
cin >> n1 >> n2 >> n3 >> n4 >> n5; friendfunc1 obj1(n1, n2, n3, n4, n5); friendfunc2 obj2;
obj2.calculateAverage(obj1);
return 0;
Output
Experiment-7
AIM- WAP that takes students marks and displays its average using friend functions.
THEORY-A friend function is defined as a function that, while not a member of a class, is
granted access to the class's private and protected members. In this context, the function
calculateAverage serves as a friend function, enabling it to access the private data members,
specifically the Marks, of the Student class. This access allows calculateAverage to compute
the average of the students' marks effectively.
ALGORITHM
1. Create a class Student to store the student's name and marks in three subjects (Math,
English,and Science) as private data members.
2. Create a constructor for the Student class to initialize the name and marks.
3. Define a displayInfo member function to display the student's name and marks.
4. Declare a friend function calculateAverage in the Student class to calculate the average of
thestudent's marks.
5. Define the calculateAverage friend function outside the class, which calculates the
average ofthe three subjects' marks.
6. In the main function, create a Student object with a name and marks, display the
student'sinformation, and calculate and display the average marks using the friend function.
CODE-
#include <iostream>
#include <string>
public:
void displayInfo() {
cout << "Math Marks: " << math << endl; cout << "English Marks: " << english << endl; cout <<
"Science Marks: " << science << endl;
};
float calculateAverage(Student s)
int main() {
student.displayInfo();
return 0;
Output
Experiment-8
THEORY- Inline functions in C++ are a valuable technique for enhancing program efficiency by
eliminating the overhead associated with standard function calls. When a function is
designated as inline, the C++ compiler integrates the function's code directly at the call site,
rather than creating a separate function call stack. This approach reduces the overhead of
function calls, potentially leading to faster program execution.
Inline functions are typically utilized for small, frequently invoked functions, where the costs
of function calls can be significant. They are defined by preceding the function declaration
with the keyword 'inline.' It is important to note that the use of inline functions serves as a
suggestion to the compiler; the decision to enforce inlining ultimately rests with the compiler
itself. Nevertheless, inline functions can be highly advantageous in contexts where
performance optimization is critical.
ALGORITHM
1. Create inline functions for each arithmetic operation (addition, subtraction, multiplication,
and division) to perform the respective operations.
2. In the 'main' function, declare variables 'num1', 'num2', and 'operation' to store the two
numbers and the desired arithmetic operation character.
3. Prompt the user to enter two numbers and the arithmetic operation.
4. Use a 'switch' statement to determine which arithmetic operation to perform based on the
'operation' character entered by the user.
5. Call the corresponding inline function and store the result in the 'result' variable.
code-
#include <iostream>
return a + b;
return a - b;
return a * b;
if (b == 0) {
return 0;
return a / b;
int main() {
char operation;
double result;
switch (operation) {
case '+':
case '-':
break;
case '*':
break;
case '/':
break;
default:
return 1;
return 0;
Output
Experiment-9
In C++, the majority of operators can be overloaded, provided that at least one of the
operands is a user-defined object. This flexibility renders C++ particularly versatile for
implementing custom data structures and classes. However, it is crucial to note that not all
operators in C++ are eligible for overloading. Additionally, operator overloading should be
approached with caution, as improper use can lead to code that is challenging to understand
and maintain.
ALGORITHM
1. Create a 'String' class to represent strings with a 'char*' data member to store the string.
2. Overload the '+' operator to perform string concatenation. Inside the operator overloading
function, allocate memory for the result string, copy the contents0 of the two strings, and
return a new 'String' object.
3. Overload the '==' operator to compare two 'String' objects by using the 'strcmp' function.
4. Overload the '<<' operator as a friend function to enable easy output of 'String' objects.
5. In the 'main' function, create 'String' objects and demonstrate string concatenation and
comparison using operator overloading.
Code-
#include <iostream>
#include <cstring>
class String {
private:
char* str;
public:
// Constructor
if (s) {
strcpy(str, s);
} else {
str = nullptr;
}
}
// Destructor
~String() {
if (str) {
delete[] str;
strcpy(result, str);
strcat(result, other.str);
return String(result);
os << s.str;
return os;
};
int main() {
} else {
return 0;
output
Experiment-10
AIM- WAP to demonstrate the use of different access specifiers by means of member
functions.
THEORY- In C++, access specifiers are essential for determining the visibility and accessibility
of elements within a class. There are three primary types of access specifiers:
Public: Class members designated as public can be accessed from any part of the
program without restrictions.
Private: Members marked as private are inaccessible from outside the class, serving to
hide the internal workings of the class.
Protected: Protected members are similar to private members but can be accessed by
subclasses (derived classes).
Access specifiers are pivotal in enforcing encapsulation and managing interactions with class
members. Public members provide an interface for interaction, private members protect
implementation details, and protected members facilitate access related to inheritance. This
concept is fundamental to object-oriented programming and is crucial for developing well-
structured and maintainable code.
ALGORITHM
1. Start
2. Include the necessary header files, especially iostream.
4. Inside the class, declare a public integer variable publicVar, a private integer variable
privateVar, and a protected integer variable protectedVar.
5. Create a constructor for the class, initializing all the variables with different values.
6. Define a public member function display() to display the values of all three variables.
CODE-
#include <iostream>
int publicVar;
AS() {
publicVar = 50;
privateVar = 60;
protectedVar = 40;
void display() {
cout << "Public Variable (publicVar): " << publicVar << endl; cout << "Private Variable
(privateVar):
cout << "Protected Variable (protectedVar): " << protectedVar << endl;
}
private:
int privateVar;
protected:
int protectedVar;
};
cout << "Accessing public variable from main: " << obj.publicVar << endl; obj.display();
// Accessing private and protected variables directly would result in compilation errors.
// cout << "Accessing private variable from main: " << obj.privateVar << endl;
// cout << "Accessing protected variable from main: " << obj.protectedVar << endl;
return 0;
Output
Experiment-11
AIM- WAP to create a member function and invoke it using "this" pointer.
THEORY- Pointers are a specific type of variable that store the memory address of another
variable. They play a crucial role in C++ programming, facilitating various functions such as
dynamic memory allocation and variable manipulation. The "this" pointer is a unique feature
in C++ that refers to the current instance of a class and is implicitly present in all non-static
member functions. It is employed to access the members—both variables and functions—of
the current object. The "this" pointer is particularly advantageous in situations where there is
ambiguity between class member variables and function parameters that share identical
names, as it clarifies that the reference pertains to the class member.
ALGORITHM
'printAddress': Prints the address of the current instance (using the "this" pointer).
'printValues': Prints the address of the current instance and two integer values passed as
parameters.
3. Call the 'printAddress' function for both 'obj1' and 'obj2' instances, which prints the
address of each instance using the "this" pointer.
4. Declare two integer variables, 'x' and 'y', and initialize them with values (x = 10, y = 20).
5. Call the 'printValues' function on 'obj1', passing the values of 'x' and 'y' as parameters. This
function prints the address of 'obj1' and the values of 'x' and 'y'. 6. Call the 'printValues'
function on 'obj2', passing different values (x = 30, y = 40) as parameters. This function prints
the address of 'obj2' and the new values of 'x' and 'y'.
Code-
#include <iostream>
class MyClass {
public:
void printAddress() {
std::cout << "Address of this instance: " << this << std::endl;
std::cout << "Address of this instance: " << this << std::endl;
std::cout << "a: " << a << ", b: " << b << std::endl;
};
int main() {
MyClass obj1;
MyClass obj2;
obj1.printAddress();
obj2.printAddress();
obj1.printValues(x, y);
obj2.printValues(30, 40);
return 0;
}
output
Experiment-12
AIM- WAP to explain virtual function and calculate area of triangle and rectangle respectively.
ALGORITHM
2. We create two derived classes 'Triangle' and 'Rectangle', each with its own implementation
of the 'area ()' function.
3. In the 'main' function, we create an array of pointers to 'Shape' objects and initialize them
with instances of 'Triangle' and 'Rectangle'.
4. We use a loop to calculate and display the areas of the shapes, taking advantage of
polymorphism to call the correct 'area ()' function for each shape.
Code-
#include <iostream>
class Shape {
public:
return 0.0;
};
private:
double base;
double height;
public:
};
private:
double length;
double width;
public:
};
int main() {
Shape* shapes[2];
std::cout << "Area of shape " << i + 1 << ": " << shapes[i]->area() << std::endl;
delete shapes[i];
return 0;
Output
Experiment-13
AIM- WAP to explain class template and member function get-max() returns the greatest of 2
numbers.
Class templates offer significant flexibility and efficiency, allowing classes to operate with
various data types while ensuring type safety. This approach minimizes code duplication,
thereby enhancing code maintainability and readability.
ALGORITHM
1. We define a class template, MaxFinder, that includes a single type parameter, T. This class
features a constructor that accepts two values of type T and includes a member
function, get_max(), which returns the maximum of the two values.
2. Within the main() function, we instantiate MaxFinder for various data types, including int,
double, and char.
3. We invoke the get_max() function on each instance to determine and display the
maximum value.
Code-
#include <iostream>
// Class template for finding the maximum of two values
class MaxFinder {
public:
T get_max() {
private:
T value1;
T value2;
};
int main() {
std::cout << "Maximum integer value: " << intMax.get_max() << std::endl;
std::cout << "Maximum double value: " << doubleMax.get_max() << std::endl;
std::cout << "Maximum character value: " << charMax.get_max() << std::endl;
return 0;
Output
Experiment-14
1. Division by zero
2. Array index
Theory
Division by Zero:
Array Indexing:
In C++, arrays are indexed starting from zero, meaning the first element is at index 0, the
second at index 1, and so forth. Accessing an array element with an index that is out of
bounds—either negative or greater than or equal to the array's size—results in undefined
behavior. This could manifest as accessing arbitrary memory locations or triggering a runtime
error.
Catch Blocks:
C++ utilizes exceptions to manage errors and exceptional events that arise during program
execution. When an error occurs, an exception can be "thrown" using the throw keyword. This
exception must subsequently be "caught" using a catch block, which contains the code to
handle the exception and determine the appropriate response. If an exception is thrown
without a corresponding catch block, the program will terminate.
Algorithm:
Code-
#include<iostream>
int main() {
try {
}
catch(const char* msg) { cerr << msg << endl;
try {
if(divisor == 0) {
return 0;
Output
Experiment-15
AIM- WAP to implement function overloading.
THEORY
Function overloading is a feature in C++ that allows multiple functions to share the same
name, provided they have different parameters. This capability enables programmers to
create functions that perform conceptually similar tasks on various data types without the
need for renaming the functions.
Key Points:
Different Parameters: Overloaded functions must differ in the number and/or type of
their parameters; they cannot vary solely by their return type.
Compile-Time Polymorphism: Function overloading exemplifies compile-time
polymorphism, as the appropriate function is resolved at compile time.
Same Scope: All overloaded functions must reside within the same scope.
Automatic Type Conversion: If a function call does not match any defined function but
could match after type conversion, C++ will automatically apply the necessary
conversions.
ALGORITHM
1. Define multiple functions with the same name, ensuring they have distinct parameter
lists.
2. When invoking the overloaded function, the compiler selects the appropriate version
based on the argument types provided.
Code-
#include <iostream>
// Function to add two integers
return a + b;
return a + b;
int main() {
int intResult;
double doubleResult;
return 0;
Output