0% found this document useful (0 votes)
22 views45 pages

EXPERIMENT-1 (24)

The document outlines several C++ programming experiments, each with specific aims and theories related to object-oriented programming concepts such as classes, encapsulation, function overloading, and constructors. Each experiment includes an algorithm, code examples, and expected outputs, covering topics like user input handling, employee management, banking systems, and friend functions. The content serves as a practical guide for understanding and implementing fundamental programming principles in C++.

Uploaded by

48 Uma shankar
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)
22 views45 pages

EXPERIMENT-1 (24)

The document outlines several C++ programming experiments, each with specific aims and theories related to object-oriented programming concepts such as classes, encapsulation, function overloading, and constructors. Each experiment includes an algorithm, code examples, and expected outputs, covering topics like user input handling, employee management, banking systems, and friend functions. The content serves as a practical guide for understanding and implementing fundamental programming principles in C++.

Uploaded by

48 Uma shankar
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/ 45

EXPERIMENT-1

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

- 1. Start the program.

2. Define a class PersonalDetails with private data members name and age.

3. Define a public member function setData() in the class PersonalDetails:

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.

6. Define another public member function getData() in the class PersonalDetails:

7. Print "Name: " followed by the value of name.

8. Print "Age: " followed by the value of age.

9. In the main() function, create an object pd of class PersonalDetails.

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.

12. End the program.

CODE-
#include <iostream>

using namespace std;

class PersonalData {

private:

int age;

string name;

public:

void setData() {

cout << "Enter your name: ";

cin >> name;

cout << "Enter your age: ";

cin >> age;

void getData() const {

cout << "\nName: " << name << "\n";

cout << "Age: " << age << "\n";

};

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.

In the example provided, we implemented function overloading to define two functions


named absoluteValue, each with distinct parameter types (int and float). When invoking this
function, the compiler determines the appropriate version to execute based on the provided
arguments. This functionality enables the calculation of absolute values for both integer and
floating-point numbers through a single, intuitively named function.

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>

using namespace std;

int absolute(int);

float absolute(float);

int main() {

int a = -5;

float b = 5.5;
cout<<"Absolute value of "<<a<<" = "<<absolute(a)<<endl;

cout<<"Absolute value of "<<b<<" = "<<absolute(b) <<endl;

system("pause");

return 0;

int absolute(int var) {

if (var < 0)

var = -var;

return var;

float absolute(float var){

if (var < 0.0)

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.

Overall, this program exemplifies how fundamental object-oriented programming (OOP)


principles—such as classes, objects, encapsulation, and methods—contribute to a structured
and modular approach to managing employee data, which can be applied to various real-
world scenarios.

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.

4. Use a loop to input employee details using the getdata() function.

5. Output the employee details using the display() function.

6. Repeat the process for each employee.

7. Display the details of all employees at the end.

CODE -

#include <iostream>

#include <string>

class Employee {
public:

int Empnumber;

std::string Empname;

void getdata() {

std::cout << "Enter Employee Number: ";

std::cin >> Empnumber;

std::cin.ignore(); // Clear the newline character from the buffer

std::cout << "Enter Employee Name: ";

std::getline(std::cin, Empname);

void display() {

std::cout << "Employee Number: " << Empnumber << std::endl;

std::cout << "Employee Name: " << Empname << std::endl;

};

int main() {

const int num_employees = 6;

Employee employees[num_employees];

for (int i = 0; i < num_employees; ++i) {

employees[i].getdata();

std::cout << "\nEmployee Details:" << std::endl;

for (int i = 0; i < num_employees; ++i) {

employees[i].display();

std::cout << std::endl;

}
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.

Encapsulation, a core principle of Object-Oriented Programming (OOP), entails grouping data


and associated methods within a class. This practice enhances data safety and integrity by
regulating access. In programming, references serve as aliases or pointers to variables,
allowing for direct alterations to the underlying data. These principles are crucial in both
procedural and object-oriented programming, playing significant roles in the structuring and
manipulation of data in software development.

ALGORITHM

For swapping value:

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.

For swapping by reference:

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>

// Function to swap two numbers using call by value

void swapByValue(int a, int b) {

int temp = a;

a = b;

b = temp;
std::cout << "Inside swapByValue function: a = " << a << ", b = " << b << std::endl;

// Function to swap two numbers using call by reference

void swapByReference(int &a, int &b) {

int temp = a;

a = b;

b = temp;

std::cout << "Inside swapByReference function: a = " << a << ", b = " << b << std::endl;

int main() {

int num1, num2;

// Input two numbers

std::cout << "Enter the first number: ";

std::cin >> num1;

std::cout << "Enter the second number: ";

std::cin >> num2;

// 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.

3. Implement member functions within the BankAccount class:

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.

4. In the main function:

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.

7. Create a menu-driven loop to interact with the bank account:

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).

9. End the program with a return statement.

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

BankAccount(const std::string& name, double initialBalance, double rate) {

accountHolder = name;

balance = initialBalance;

interestRate = rate;

// Function to deposit money into the account

void deposit(double amount) {

if (amount > 0) {

balance += amount;

std::cout << "Deposited $" << amount << " into the account." << std::endl;

} else {

std::cout << "Invalid deposit amount." << std::endl;

}
// Function to withdraw money from the account

void withdraw(double amount) {

if (amount > 0 && amount <= balance) {

balance -= amount;

std::cout << "Withdrawn $" << amount << " from the account." << std::endl;

} else {

std::cout << "Invalid withdrawal amount or insufficient balance." << std::endl;

// Function to calculate interest on the account balance

void calculateInterest() {

double interest = balance * (interestRate / 100);

balance += interest;

std::cout << "Interest added: $" << interest << std::endl;

// Function to display the account details

void displayAccount() {

std::cout << "Account Holder: " << accountHolder << std::endl;

std::cout << "Current Balance: $" << balance << std::endl;

std::cout << "Interest Rate: " << interestRate << "%" << std::endl;

};

int main() {

std::string name;

double initialBalance, rate;

std::cout << "Enter the account holder's name: ";


std::cin >> name;

std::cout << "Enter the initial balance: ";

std::cin >> initialBalance;

std::cout << "Enter the interest rate (%): ";

std::cin >> rate;

// Create a BankAccount object using the constructor

BankAccount account(name, initialBalance, rate);

int choice;

do {

std::cout << "\nBank Account Menu:\n";

std::cout << "1. Deposit\n";

std::cout << "2. Withdraw\n";

std::cout << "3. Calculate Interest\n";

std::cout << "4. Display Account Details\n";

std::cout << "5. Exit\n";

std::cout << "Enter your choice: ";

std::cin >> choice;

switch (choice) {

case 1:

double depositAmount;

std::cout << "Enter the deposit amount: $";

std::cin >> depositAmount;

account.deposit(depositAmount);

break;

case 2:

double withdrawAmount;
std::cout << "Enter the withdrawal amount: $";

std::cin >> withdrawAmount;

account.withdraw(withdrawAmount);

break;

case 3:

account.calculateInterest();

break;

case 4:

account.displayAccount();

break;

case 5:

std::cout << "Exiting the program. Goodbye!" << std::endl;

break;

default:

std::cout << "Invalid choice. Please select a valid option." << std::endl;

} while (choice != 5);

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

1. Define two classes friendfunc1 and friendfunc2

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

4. Declare a friend function calculateAverage in class friendfunc1. This function will


bedefined in class friendfunc2.

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>

using namespace std;

class friendfunc2; // Forward declaration

class friendfunc1 {

public:
int num[5];

friendfunc1(int a, int b, int c, int d, int e) { num[0] = a;

num[1] = b;

num[2] = c;

num[3] = d;

num[4] = e;

friend void calculateAverage(friendfunc2, friendfunc1); // Friend function

};

class friendfunc2 { public:

void calculateAverage(friendfunc1 obj) { double sum = 0;

for(int i=0; i<5; i++) { sum += obj.num[i];

cout << "Average: " << sum/5 << endl;

};

int main() {

float n1, n2, n3, n4, n5;

cout << "Enter five numbers: ";

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>

using namespace std;

class Student { private:

string name; int math;

int english; int science;

public:

Student(std::string n, int m, int e, int s) : name(n), math(m), english(e), science(s) {}

void displayInfo() {

cout << "Student Name: " << name << endl;

cout << "Math Marks: " << math << endl; cout << "English Marks: " << english << endl; cout <<
"Science Marks: " << science << endl;

friend float calculateAverage(Student s);

};

// Friend function to calculate average

float calculateAverage(Student s)

return (s.math + s.english + s.science) / 3.0;

int main() {

Student student("Uma Shankar", 85, 95, 90);

student.displayInfo();

cout << "Average Marks: " << calculateAverage(student) << endl;

return 0;

Output
Experiment-8

AIM- WAP to perform different arithmetic operations using inline functions.

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.

6. If the user enters an invalid operation, display an error message.

7. Display the result to the user

code-

#include <iostream>

// Inline function for addition

inline double add(double a, double b) {

return a + b;

// Inline function for subtraction


inline double subtract(double a, double b) {

return a - b;

// Inline function for multiplication

inline double multiply(double a, double b) {

return a * b;

// Inline function for division

inline double divide(double a, double b) {

if (b == 0) {

std::cerr << "Error: Division by zero!" << std::endl;

return 0;

return a / b;

int main() {

double num1, num2;

char operation;

std::cout << "Enter two numbers: ";

std::cin >> num1 >> num2;

std::cout << "Enter the arithmetic operation (+, -, *, /): ";

std::cin >> operation;

double result;

switch (operation) {

case '+':

result = add(num1, num2);


break;

case '-':

result = subtract(num1, num2);

break;

case '*':

result = multiply(num1, num2);

break;

case '/':

result = divide(num1, num2);

break;

default:

std::cerr << "Invalid operation" << std::endl;

return 1;

std::cout << "Result: " << result << std::endl;

return 0;

Output
Experiment-9

AIM- WAP to perform string operations using operator overloading in C++.

THEORY-Operator overloading in C++ is a robust feature that enables the redefinition of


operator behavior for user-defined types or objects. This capability assigns a specific
meaning to an operator when applied to custom data types. When an operator is overloaded,
the compiler incorporates the function's code directly at the call site, rather than creating a
separate function call stack. This approach minimizes function call overhead, potentially
resulting in enhanced program execution speed.

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.

In summary, operator overloading significantly enhances the expressiveness of C++, allowing


user-defined types to function in intuitive and comprehensible ways. This feature is integral
to the power and flexibility that C++ offers.

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

String(const char* s = nullptr) {

if (s) {

str = new char[strlen(s) + 1];

strcpy(str, s);

} else {

str = nullptr;

}
}

// Destructor

~String() {

if (str) {

delete[] str;

// Overload the + operator for string concatenation

String operator+(const String& other) const {

char* result = new char[strlen(str) + strlen(other.str) + 1];

strcpy(result, str);

strcat(result, other.str);

return String(result);

// Overload the == operator for string comparison

bool operator==(const String& other) const {

return strcmp(str, other.str) == 0;

// Overload the << operator for output

friend std::ostream& operator<<(std::ostream& os, const String& s) {

os << s.str;

return os;

};

int main() {

String s1("Hello, ");


String s2("world!");

String s3 = s1 + s2; // Concatenation using operator overloading

std::cout << "s1 + s2 = " << s3 << std::endl;

String s4("Hello, world!");

if (s3 == s4) { // Comparison using operator overloading

std::cout << "s3 and s4 are equal." << std::endl;

} else {

std::cout << "s3 and s4 are not equal." << std::endl;

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.

3. Define a class AS.

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.

7. In the main function:

Create an object of the A class.


Access the public variable directly and display its value.
Call the display() member function to display the values of all three variables.
Attempt to access the private and protected variables directly (commented out),
whichwould result in compilation errors.

CODE-

#include <iostream>

using namespace std;

class AS{ public:

int publicVar;

AS() {

publicVar = 50;

privateVar = 60;

protectedVar = 40;

void display() {

cout << "Public Variable (publicVar): " << publicVar << endl; cout << "Private Variable
(privateVar):

" << privateVar << endl;

cout << "Protected Variable (protectedVar): " << protectedVar << endl;

}
private:

int privateVar;

protected:

int protectedVar;

};

int main() { AS obj;

cout << "Accessing public variable from main: " << obj.publicVar << endl; obj.display();

// Accessing private and protected variables directly would result in compilation errors.

// Uncommenting the following lines will demonstrate those 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

1. Define a class 'MyClass' with the following member functions:

'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.

2. In the 'main' function:

Create two instances of the 'MyClass' class, 'obj1' and 'obj2'.

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'.

7. The program ends.

Code-

#include <iostream>

class MyClass {

public:

void printAddress() {

std::cout << "Address of this instance: " << this << std::endl;

void printValues(int a, int b) {

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();

int x = 10, y = 20;

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.

THEORY- Virtual functions are a crucial aspect of object-oriented programming in C++.


Theyenable a function in a base class to be superseded by a function in a subclass. If a
function is marked as virtual in the base class, it can be redefined in the subclasses. This
becomes particularly beneficial when dealing with a class hierarchy and there's a need to
offer varying implementations of the same function depending on the subclass.

ALGORITHM

1. We define a base class 'Shape' with a virtual function 'area ()'.

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.

5. Finally, we clean up the dynamically allocated objects to avoid memory leaks.

Code-
#include <iostream>

class Shape {

public:

virtual double area() {

return 0.0;

};

class Triangle : public Shape {

private:

double base;

double height;

public:

Triangle(double b, double h) : base(b), height(h) {}

double area() override {

return 0.5 * base * height;

};

class Rectangle : public Shape {

private:

double length;

double width;

public:

Rectangle(double l, double w) : length(l), width(w) {}

double area() override {

return length * width;


}

};

int main() {

Shape* shapes[2];

shapes[0] = new Triangle(5.0, 8.0);

shapes[1] = new Rectangle(4.0, 6.0);

for (int i = 0; i < 2; i++) {

std::cout << "Area of shape " << i + 1 << ": " << shapes[i]->area() << std::endl;

// Clean up the dynamically allocated objects

for (int i = 0; i < 2; i++) {

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.

THEORY- Class templates in C++ are a fundamental aspect of generic programming,


facilitating code reusability and enabling the handling of multiple data types within a single
class or function. A class template is defined using the template keyword, followed by
template parameters enclosed in angle brackets < >. These parameters can represent any
type and are specified when an object of the template class is instantiated.

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

template <typename T>

class MaxFinder {

public:

MaxFinder(T a, T b) : value1(a), value2(b) {}

T get_max() {

return (value1 > value2) ? value1 : value2;

private:

T value1;

T value2;

};

int main() {

// Create instances of MaxFinder with different data types

MaxFinder<int> intMax(10, 30);

MaxFinder<double> doubleMax(3.14, 2.71);

MaxFinder<char> charMax('A', 'Z');

// Find the maximum values and display them

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

AIM- WAP to illustrate

1. Division by zero

2. Array index

3. Also use multiple catch blocks

Theory

Division by Zero:

In mathematics, division by zero is considered undefined, as it results in contradictions or


nonsensical outcomes. In C++, attempting to divide a number by zero will either trigger a
runtime error or yield an undefined result due to the inability to perform the operation
meaningfully.

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:

1. Start the program.


2. Initialize an array named arr of size 5 with values {1, 2, 3, 4, 5}.
3. Set the index to 6 (an out-of-bounds index for the array) and the divisor to 0 (which will
cause division by zero).
4. Begin the first try block:
If the index is less than 0 or greater than or equal to 5 (the size of the array), throw an
exception with the message “Index out of bounds!”.
If no exception is thrown, print the array element at the specified index.
5. Begin the first catch block:
Catch the exception and print the error message.
6. Begin the second try block:
If the divisor is zero, throw an exception with the message “Division by zero!”.
If no exception is thrown, print the result of dividing 10 by the divisor.
7. Begin the second catch block:
Catch the exception and print the error message.
8. End the program.

Code-

#include<iostream>

using namespace std;

int main() {

int arr[5] = {1, 2, 3, 4, 5};

int index = 6; // Out-of-bounds index

int divisor = 0; // Zero divisor

try {

if(index < 0 || index >= 5) { throw "Index out of bounds!";

cout << "Array element: " << arr[index] << endl;

}
catch(const char* msg) { cerr << msg << endl;

try {

if(divisor == 0) {

throw "Division by zero!";

cout << "Division result: " << 10 / divisor << endl;

catch(const char* msg) { cerr << msg << endl;

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

int add(int a, int b) {

return a + b;

// Function to add two double values

double add(double a, double b) {

return a + b;

int main() {

int intResult;

double doubleResult;

intResult = add(7, 9); // Calls the first function (int version)

doubleResult = add(3.5, 2.2); // Calls the second function (double version)

std::cout << "Sum of integers: " << intResult << std::endl;

std::cout << "Sum of doubles: " << doubleResult << std::endl;

return 0;

Output

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy