OOPS EXPERIMENTS
Experiment 1
AIM:
1. Write a program to print “Hello World” in C++.
2. Write a program to perform the addition of two numbers in C++.
3. Perform the sum of natural numbers in C++.
4. Implement any type of sorting of N numbers.
Experiment 2
Arrays and Pointers
ASSUMPTION: Assume there are three integer elements in the
array A= {10,100,200} and are stored at addresses 0xbfa088b0,
0xbfa088b4, 0xbfa088b8. Note: The address can vary from system
to system.
AIM:
1. WAP in C++ to perform the following operations using pointer
arithmetic. a.) Increment a Pointer (++) and sample output after
incrementing pointer: Address of var[0] = 0xbfa088b0, Value of
var[0] = 10, Address of var[1] = 0xbfa088b4 Value of var[1] = 100,
Address of var[2] = 0xbfa088b8 Value of var[2] = 200 b.)
Decrement a Pointer (--) and sample output after decrementing
pointer: Address of var[3] = 0xbfdb70f8, Value of var[3] = 200,
Address of var[2] = 0xbfdb70f4 Value of var[2] = 100, Address of
var[1] = 0xbfdb70f0, Value of var[1] = 10.
2. WAP that manages bank information using dynamic memory
allocation. Define a structure called Bank with fields like bank
name, branch, number of accounts, and highest balance.
Dynamically allocate memory for an array of ‘n’ banks and input
their details. Prompt the user to input information and display the
following
a.) Display the name and branch of the bank with the third-highest
balance.
b.) Delete the record and display it
c.) Add the record and display it.
Experiment 3
CLASSES & OBJECTS
Q1. Define a class to represent a bank account. Include the
following members:
a. Data Members.
i. Name of the depositor
ii. Account Number
iii. Type of account
iv. Balance amount in the account.
b. Member Function.
i. To assign initial values.
ii. To deposit an amount.
iii. To withdraw an amount after checking the balance.
iv. To display name and balance, write a main function to test
the program.
Q2. Write a class to represent a vector (a series of float values),
including a member function to perform the following tasks: a. To
create the vector b. To modify by a scalar element c. To multiply
by a scalar value d. To display the vector in the form (10, 20, 30 …)
Q3. WAP in C++ to demonstrate the following:
(i) Create a class called First with a data member as a string
student name, and a member function called print name.
(ii) (ii) Your program should print the student's name by
accessing the member function.
Q4. Write a C++ program to print the area of a rectangle by
creating a class named Area having two functions. First named
setDim() that takes the length and breadth of the rectangle, and
the second named getArea() that returns the area of the
rectangle.
Experiment 4
CONSTRUCTORS
Q1. WAP in C++ with the following requirements:
(i) Create a class called Second with an int type person ID
(ii) Create a default and parameterized constructors
(iii) Create two objects. obj1 will call the default constructor to
print person id, and obj1 will call the parameterized
constructor to print person id.
Q2. Write a C++ program to create a class that can hold private
data members such as – Enrolment number, Name, Branch, and
CGPA. Include the constructors for initialising data members as
follows,
(i) Initialise the enrolment no., name, branch, and CGPA.
(ii) Initialise the enrolment no., name, CGPA (Default
branch=’CSE’).
(iii) Initialise enrolment no., name, branch, and CGPA with
default values [1, “Unknown”, “CSE”, 6]. Also include get
and set functions for each of the data members. Create
objects to call different constructors and update the CGPA
value of any of the objects created. Display the updated
CGPA along with the student’s details on the console.
Q3. Write a C++ program to calculate the electricity bill using a
Class
i. To calculate the Electricity Bill of a Person using Class,
first create and call the get( ) function to take input
details of the customer.
ii. Create and call a new function, i.e, calc_bill( ), to
calculate the total bill of the customer on behalf of the
units consumed by the customer. iii. Create the put( )
function to print or display a customer's or person's
electricity bill on the screen.
Q4. Create a class Rectangle with private data members length
and breadth. Implement a default constructor that sets both
dimensions to 1, and a parameterized constructor that accepts
values for length and breadth. Write a member function to
calculate the area and demonstrate both constructors.
Experiment 5
Copy Constructor, Destructor, Static Data Member & Friend
Function
1. What would be the output of the following program in C++?
#include<iostream>
using namespace std;
class Location
{
private:
int a, b;
public:
Location(inta1, intb1)
{
a = a1;
b = b1;
}
}// Copy constructor Location(cons Location &l2)
{a = l2.a; b = l2.b; }
int getA ()
{ return a; }
int getB ()
{ return b; }
};
int main()
{
Location l1(10, 15); // Normal constructor is called here
Location l2 = l1; // Copy constructor is called here
return 0;
}
2. WAP in C++ to create a class Wall having private data members
length and height. Create a parameterized constructor and a copy
constructor to initialize these private data members. Define a
member function to return the area. Demonstrate the working of
each member function.
3. Create a class String with two private members (char * s; and
int size;) to store a string and it’s length. Define a constructor, a
copy constructor and a destructor. Add a member function that
prints the string. Demonstrate the working of each function.
4. What is the output of the following program?
#include<iostream>
using namespace std;
class Demo
{
private:
//static data members
static int X;
static int Y;
public:
//static member function
static void Print ()
{
cout <<"Value of X: " << X << endl; cout <<"Value of Y: " << Y <<
endl;
}
};
//static data members initializations
int Demo :: X =10;
int Demo :: Y =20;
int main()
{
Demo OB;
//accessing static function with object name
cout<<"Printing through object name:"<<<"Printing through class
name:"<
Demo:: Print()
return 0;
}
EXPERIMENT 6
VIRTUAL
Q1) Write a C++ program given that there are two base classes
namely class A and class B from which class C is inherited. The
class A contains member function getBase() and reads “Base”
value as user input from keyboard. Class B contains member
function getHeight() and reads “Height” value as user input from
keyboard. The derived class C inherits all the public members of A
and B and computes the area of the triangle.
SAMPLE OUTPUT:
enter value of base: 4.5
enter value of height: 78
area = 175.5
Q2) Write a C++ program, consider that there are two base
classes namely class StudentsDetails and class Marks from
which class C is inherited. The class StudentsDetails contains
member function getDetails() that reads “students name”,
“Enrollment number” value as user input from keyboard. Class
Marks contains member function getMarks() and reads “5 subject
marks” value as user input from keyboard. The derived class C
inherits all the public members of StudentsDetails and class
Marks and calculates total marks.
SAMPLE OUTPUT:
enter value of name: JOHN
enter value of eno.: JOHN123
enter value of marks [0] 89
enter value of marks [1] 78
enter value of marks [2] 67
enter value of marks [3] 86
enter value of marks [4] 57
Total = 377 .
Q3) Based on the virtual function concept, write the main
function for the following code to display the derived class values
given by user at run time.
#include<iostream>
using namespace std;
class base
{
public:
char fname[20];
char surname[20];
public:
virtual void calculate()
{
cout<< "enter fname:"; cin>>fname;
cout<< "enter surname"; cin>> surname;
}
void display()
{
cout<< "welcome" <<fname<< surname<<< "enter
derived_fname:"; cin>>fname;
cout<< "enter derived_ surname"; cin>>surname;
}
void display()
{
cout<< "welcome to derived" <<fname<< surname<<endl;
}
};
int main()
}
{
WRITE CODE HERE
}
Q4) Given a snippet of the program to create a base class named
as base_food_Itemswith a virtual function named as order and
total_Price. Create a derived class name Chinese. Then calculate
the total_price of food items based on variables quantity and
item_price.
#include <iostream>
using namespace std;
class base_food_items
{
public:
char item_name[20];
int quantity; int item_price;
public: virtual void order()
{
cout<< "enter item name:"; cin>>item_name; cout<< "enter
quantity"; cin>> quantity;
cout<< "Item price"; cin>>item_price;
}
void total_price()
{ cout<<"order is: "
<<item_name<<"\t"<<"quantity:"<<quantity<<< "total price="
<<item_price*quantity<<endl;
}
};
Q5) Write a C++ program to show the functionality of the abstract
classes.
Output :
This is Display 1() method of Derived Class
This is Display 2() method of Derived Class.
Q6) Write a program to use constructors of the abstract class to
find the sum of two numbers and display the results.
EXPERIMENT 7
GENERIC PROGRAMMING
Q1. Predict the output of following program.
template <typename T>
void abcd(const T&x)
{
static int count = 0; cout << "x = " << x << " count = " << count <<
endl; ++count; return;
}
int main()
{
abcd (1);
cout << endl; abcd(1);
cout << endl; abcd(1.1); cout << endl;
return 0;
}
Q2. Predict the output of the following program. template class.
template<class T> int main()
class Test {
{ Test a;
private: Test b;
T val; Test c;
public: cout << Test::count << endl;
static int count; Test() cout << Test::count << endl;
{count++; } return 0;
}; template int Test::count = 0; }
Q3. Create a template class calculator to perform addition,
subtraction, multiplication and division of two numbers. Show the
results for different datatypes.
Q4. Write templates for the two functions, namely minimum and
maximum. Minimum function should accept two arguments and
return the value of the arguments that is the lesser among the
two. Maximum function should accept two arguments and return
the value of the arguments that is the greater among the two
values. Design a simple driver program that demonstrates the
templates with various data types.
Q5. Create your own template class MyVector with data members
and member functions such that the size(), push_back() and
pop_back() functionalities of Vector can also be performed by
MyVector.
EXPERIMENT 8
CONSOLE I/O and FILE HANDLING
1. Write a program that reads a text from the keyboard and
displays the following information on the screen in two columns:
(a) Number of lines
(b) Number of words
(c) Number of characters
Strings should be left-justified and numbers should be right-
justified in a suitable field width.
2. Write a program to read a list containing item name, item code,
and cost interactively and produce a three-column output as
shown below.
NAME CODE COST
Turbo C++ 1001 250.95 C
Primer 905 95.70
..... ... .....
..... ... .....
Note that the name and code are left-justified, and the cost is
right-justified with a precision of two digits. Trailing zeros are
shown.
3. Write a program that reads a text file and creates another file
that is identical except that every sequence of consecutive blank
spaces is replaced by a single space.
4. A file contains a list of telephone numbers in the following
form: John 23456, Ahmed 9876. The names contain only one
word, and the names and telephone numbers are separated by
white spaces. Write a program to read the file and output the list
in two columns. The names should be left-justified and the
numbers right-justified.
5. Write a program that will create a data file containing the list of
telephone numbers given in Q4. Use a class object to store each
set of data.
6. Write an interactive, menu-driven program that will access the
file created in Q5 and implement the following tasks.
(a) Determine the telephone number of the specified person.
(b) Determine the name if a telephone number is known.
(c) Update the telephone number whenever there is a change.
EXPERIMENT 9
EXCEPTION HANDLING
1. Write a program to implement the exception handling with
multiple catch Statements. You have to take three input values
from user as Integer value, Character value and double value. For
each above values you’ll have to handle it with the catch
statement.
2. What output is produced by the following code?
int wait_time = 46;
try
{
cout << "Try block entered.\n"; if (wait_time > 30) throw wait_time;
cout << "Leaving try block.\n";
}
catch(int thrown_value)
{
{
cout << "Exception thrown with\n"<< "wait_time equal to " <<
thrown_value << endl;
}
cout << "After catch block." << endl;
3. What would be the output produced by the code in Question 2
if we make the following change? Change the line
int wait_time = 46;
to
int wait_time = 12;
4. What happens when a throw statement is executed? This is a
general question. Tell what happens in general, not simply what
happens in the code in Question 2 or some other sample code.
5. What is the output produced by the following program?
#include<iostream>
using namespace std;
void sample_function(double test) throw (int);
int main()
{ try
{ cout << "Trying.\n"; sample_function(98.6); cout << "Trying after
call.\n"; }
catch(int)
{ cout << "Catching.\n";
}
cout << "End of program.\n";
return 0;
}
void sample_function(double test) throw (int)
{
cout << "Starting sample_function.\n";
if (test < 100) throw 42;
}
6. What is the output produced by the program in Question 5 if the
following change were made to the program? Change
sample_function(98.6); in the try block to sample_function(212);
7. What happens when an exception is never caught?
8. Can you nest a try block inside another try block?
9. What will be the output of the following code snippet?
void myFunction(int test)
{
try
{
if (test) throw test; else throw "Value is zero";
}
catch (int i)
{
cout << "CaughtOne " ;
}
catch (const char *str)
{
cout << "CaughtString ";
}
}
int main()
{ myFunction
(1); myFunction(2); myFunction(0); myFunction(3);
return 0;
}
a) CaughtOne CaughtOne CaughtString CaughtString
b) CaughtOne CaughtString CaughtString CaughtOne
c) CaughtOne CaughtOne CaughtOne CaughtOne
d) CaughtOne CaughtOne CaughtString CaughtOne .
10. What will be the output of the following code snippet?
#include<iostream>
using namespace std;
struct MyException :
public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
int main()
{
try
{
throw MyException();
} catch(MyException& e)
{
std::cout << "MyException caught" << std::endl; std::cout <<
[Link]() << std::endl;
}
catch(std::exception& e)
{
std::cout << "Exception caught" << std::endl; std::cout <<
[Link]() << std::endl; }
}
a)zMyException caught
C++ Exception
b)C++ Exception
MyException caught
c)Exception caught
C++ Exception
d)C++ Exception
MyException caught Exception caught.
EXPERIMENT 10
STANDARD TEMPLATE LIBRARY
1. Create a map named Students where the keys will be integers
(RollNo), and the values will be strings (Name). Insert values into
the map Students. A key of 200 and a value of Alice will be
inserted into the map. Insert values into the map Students. A key
of 201 and a value of John will be inserted into the map. Use the
size() function to get the size of the map named Students. Use a
for loop to create an iterator named it to iterate over the elements
of the map named Students. Print the values of the map Students
on the console.
2. Create a map named m where the keys will be integers, and the
values will be integers. Three entries have been made into the
map. Insert a new entry into the map m. A key of 5 and a value of 6
will be inserted into the map. You can enter items into std::map
using the insert() function. Remember that the std::map keys
must be unique. So, it first checks whether each key is present in
the map. If it's present, the entry will not be inserted, but it returns
the iterator for the existing entry. If it's not present, the entry is
inserted. Use the insert_or_assign() function to insert or modify
an existing entry. Use a for loop to create an iterator named itr to
iterate over the elements of the map named m. Print the values of
the map m on the console.
3. Create a map named Students whose keys will be integers and
values strings. Insert values into the map Students. A key of 200
and a value of Alice will be inserted into the map. Insert values
into the map Students. A key of 201 and a value of John will be
inserted into the map. You can use the find() function to search for
elements in a map by their keys. If the key isn't found, the function
returns std::map::end. Otherwise, an iterator of the searched
element will be returned. Look for the value associated with a key
of 201. Use an if statement to check whether the value for the key
is found. Print the value of the key alongside some text on the
console.
4. Create a map named my_map whose keys will be strings and
values integers. Insert values into the map my_map. A key of Cow
and a value of 1 will be inserted into the map. Insert values into
the map my_map. A key of Cat and a value of 2 will be inserted
into the map. Add a value 3 into the map my_map with a key of a
lion. Create an iterator to iterate over the map my_map looking for
the key cat. You can use the erase() function to delete a value
from a map. You simply create an iterator that points to the
element to be deleted. The iterator is then passed to the erase()
function. Delete the element pointed to by the iterator. Use an
iterator to iterate over the elements of the map my_map from the
start to the end. Print out the contents of the map my_map on the
console.
5. WAP in C++ to store the information entered by the user into
the file.
6. WAP in C++ to retrieve information from the file that is entered
in Q5.
7. WAP in C++ to Copy Content of One File to Another. You have to
ask from user to enter the name of the source file (with extension)
and the target file (with extension).
8. Write a program in C++ that merges the content of two files into
the third file. To merge two files in C++ programming, you have to
ask from user to enter the names of all three files with extensions
9. Write a program in C++ that deletes a file from the current
directory. To delete any file from the current directory, you have to
ask from user to enter the name of file first and then perform the
operation of deleting it from the directory.
10. WAP in C++ which opens a file in reading and writing mode.
After writing information inputted by the user to a file named
[Link], the program reads information from the file and outputs
it onto the screen.