Sunteți pe pagina 1din 22

Programming in C++ Lab

CCS208/CCS208R01
(Common for all Branches of I Year B.Tech)

2016-17 Even Semester


List of Exercises
1. Programs using Branching

2. Programs using Multi Dimensional Array

3. Programs using Function Overloading and Inline Functions

4. Programs using Classes and Objects (Array as Data Member and Array of
Objects)

5. Programs using Constructors and Destructor

6. Programs using string class

7. Programs using Operator Overloading

8. Programs for Data Conversion using Overloading

9. Programs using Inheritance

10. Programs using Virtual Functions and Friend Functions

11. Programs using Templates

12. Programs using Files

13. Dividing Large Program into Multiple Files


Ex.No:1 Programs using Branching
Objective:

To understand the concept of branching statements in C++.

Pre-Lab:
Simple programs to understand the use of cin, cout and branching statements.
Program to generate prime factors.
Program that reads an integer n as input and computes u(n) as follows: u(0)=3, u(n+1)=3*u(n)
+4

Exercises:
a) Format the display

By default, output is right justified in its field. You can display left justified text output using the
manipulator setiosflags(ios::left). Use this manipulator along with setw(), display the following
output:

Algorithm:
1. Get firstname, lastname, street, Address, Town and state from the user.
2. Display all the details in the specified format using setiosflags (ios::left) and setw
manipulator.

b) ATM pin verification

Write a program which takes PIN number of the user as input and then verifies his pin. If pin is
verified, the program shall display Pin verified.. Welcome; otherwise, the program shall
give user another chance. After 3 wrong attempts, the program shall display Limit expired and
then exit. Use for loops to implement the logic.
Algorithm:
1. Input different PIN numbers and store them in an array.
2. Get the pin number of the user as input.
3. Check if the PIN given by the user is present in the array.
4. If PIN is found, display Pin Verified.. Welcome. Else, ask the user to re-enter the
PIN.
5. After three consecutive unsuccessful attempts, display Limit expired.
Sample input and output:
Enter the PIN no : 1234
Your PIN no is wrong. Enter correct PIN no.
2256
Pin Verified.. Welcome

c) Calculator design

Create the equivalent of a simple arithmetic calculator. The program should ask the user to enter
a number, an operator and another number (floating Point). It should then carry out the specified
arithmetic operation: Add, Subtract, Multiply or Divide. Use switchcase statement to select the
operation, do the calculation and display the result.
Algorithm:
1. Get the number, an operator and another number. Declare all the numbers as float.
2. Use switchcase statement to select the operation.
3. Perform specified operation given by the user.
4. Display the result.

Sample input and output:


Enter first number: 10
Enter the operator: /
Enter second number: 3
Answer = 3.3333

Ex.No:2 Programs using Multidimensional array

Objective:

To understand the concept of multidimensional array.

Pre-Lab:
Write a program that allows the user to input integer numbers, and then store them in an int
array. Write a function called maxint() that searches the array for the largest one. The function
should take as arguments the address of the array and the number of elements in it, and return the
index of the largest element. The main program should call this function and then display the
largest element and its index.
Exercises:

a) Write a program to check whether the given matrix is Symmetric, Skew symmetric, Diagonal
or Identity.
Algorithm:
1. Take the elements of the matrix as input in a two dimensional array.
2. For symmetric matrix: condition is aij = aji.
3. For skew-symmetric matrix: conditon is aij = aji, where i != j .
4. Diagonal matrix: aij = 0, where i != j.
5. Identity Matrix: (aij = 1 , where i=j) and ( aij = 0, where i!=j)
6. Display the result.

Sample input and output:


Enter number of rows and columns for Symmetric 3 3
513
102
325
It is Symmetric matrix
Enter number of rows and columns for Skew Symmetric 3 3
5 1 3
-1 0 2
-3 -2 5
It is Skew Symmetric matrix
Enter number of rows and columns for diagonal matrix 3 3
100
020
003
It is diagonal matrix.
Enter number of rows and column for Identity matrix 3 3
100
010
001
It is diagonal, identity matrix.

Ex.No:3. Programs using Function Overloading and Inline Functions

Objective:

To study the concept of function overloading and inline function.

Pre-Lab:
Write a C++ Program to find the area of Square, Rectangle, Circle and Triangle using
function overloading.

Exercises:
a) Raising a number N to the power P is the same as multiplying N by itself P times. Write a
function called power() that takes N (double) and P (int) as input, and returns the result N P as a
double value. Use a default argument of 2 for P, so that if this argument is omitted, the number N
will be squared. Overload power() function, to work with int, long, and float. Overload the
power() function for char datatype also, which should print P times the given character N. Write
the main() program to exercise these overloaded functions with all argument types.
Algorithm:
1. Get values for N and P as input from the user.
2. Overload power function to find NP. N can be of any data type.
3. Use a default value of 2 for P.
4. Display the result.
Sample input and output:
Enter the N and P : 2 3
Result: 8
Enter the N and P : 2.3 5
Result:64.36
Enter the N and P : x 5
Result: xxxxx

b) Write an inline function called negtopos() that accepts an int argument by reference and
changes the number to positive, if it is negative. Write a main() program to test this function.
Algorithm:
1. Get the number from the user.
2. Invoke inline function negtopos(), to convert the number to positive, if it is negative.
3. Display the result.

Sample input and output:


Enter the number: -3
Result: 3

Ex.No:4. Programs using Classes and Objects (Array as Data Member and
Array of Objects )

Objective:

To understand the concept of classes and objects (Array as Data Member and Array of
Objects).

Pre-Lab:
Create a class called CarParking that has data members car
_id (int), Rate (float) and Duration(int). Include two member functions - (i) to take input and (ii)
calculate charges and show the result.
Exercises:
a) Create a class called Employee that has data members - EmpName (char array) and EmpNo
(long). Include member functions (i) getData() to get data from the user for an object, (ii)
putData() to display the object details in a formatted manner. Assume the name has no
embedded blanks. Write the main() program to create an array of objects of the class Employee,
take user to input for n employees and print employee details in a formatted manner (use setw,
setiosflags).
Algorithm:
1. Create a class called Employee
2. Declare two data members (EmpName and EmpNo)
3. Include a member function getdata() - to get data from the user
4. Include another member function putdata() - to display details
5. Create an array of objects to hold n employees details
6. Read employee details by invoking getdata() function
7. Display the employees details by calling the function putdata()
Sample input and output:
Enter three employee details:
Name:Alpha
Empno:1
Name:Beta
Empno:2
Name:Gama
Empno:3

Emp no Empname
1 Alpha
2 Beta
3 Gama

b) Program to find the average of the given n objects of Distance class, stored in an array.

Algorithm:
1. Create a class called Distance.
2. Declare two data members - Feet (int), Inch (float)
3. Include the following member functions:
a. GetData() - to read input for an object.
b. DistToFloat() - to convert the object into inches
c. FloatToDist() to convert the calculated inches back into Distance object
d. PutData() - to display the Distance object in proper format
4. Declare an array of objects of Distance class in main().
5. Invoke GetData() to read n objects.
6. Find the average of these n Distance objects, after converting them to inches(float) using
DistToFloat() member function.
7. Convert the average (in inches) to Distance object by invoking FloatToDist() function.
8. Display the result using PutData() function.

Sample input and output:


No. of objects: 3
Enter the object details:
Obj 1: Feet : 1 Inch : 10.0
Obj 2: Feet : 2 Inch : 8.0
Obj 3: Feet : 10 Inch : 7.0

Average : 15 1.0

Ex.No:5. Programs using Constructors and Destructor

Objective:
To understand the concept of Constructors and Destructors.

Pre-Lab:
Create a class for counting the number of objects created and destroyed within various blocks
using constructors and destructor.
Exercises:
a) Create a class Time with data members Hours(int), Minutes(int) and Seconds(int). Include
two constructors (i) to initialize the data members to zero, and (ii) to initialize the data
members with the values passed as arguments. Include two member functions (i) AddTime()
to add two objects passed as parameters and set the invoking object with this result (ii)
DispTime() to display the time in the format hh:mm:ss. The main() program should create two
initialized Time objects and one that is not initialized. Add the two initialized values leaving the
result in the third Time object. Display the values of the third object.
Algorithm:
1. Create a class Time with data members Hours(int), Minutes(int) and Seconds(int).
2. Include two constructors :
a. to initialize the data members to zero
b. to initialize the data members with the values passed as arguments.
3. Include two member functions :
a. AddTime() to add two objects passed as parameters and set the invoking object
with this result
b. DispTime() to display the time in the format hh:mm:ss
4. Write the main() program to create two initialized Time objects and one that is not
initialized.
5. Add the two initialized values leaving the result in the third Time object.
6. Display the values of the third object.

Sample input and output:

Enter time 1: 2 11 23
Enter time 2: 3 55 30
Result: 06:06:53
b) Program to create an array of objects of class Details with data members Name(char array),
Area(char array) and Phone_no(char array in the format : areacode-ph.no). Include a 4-argument
constructor that concatenates the area code with phone no., using strcat function. Include a member
function to display the object details in a formatted manner.
Algorithm:
1. Create a class called Details with data members Name(char array), Area(char array) and
Phone_no(char array in the format : areacode-ph.no).
2. Include a constructor with name, area, phno and areacode as arguments. It initializes the
Name and Area data members with the first two arguments. It concatenates the areacode with
phno, using strcat function and initializes the Phone_no with this string.
3. Include a member function to display the object details in a formatted manner.
4. In the main() program, declare an array of objects and get the number of objects n.
5. Use temporary char arrays to read each object details, initialize a dummy object with these
details, using 4-argument constructor.
6. Assign this object to the corresponding element of the array of objects.
7. Display the details of all the n objects in a formatted manner.

Sample input and output:


No of customers: 2
Customer 1 (name, area, phno, areacode): Alpha Trichy 2554032 0431
Customer 2 (name, area, phno, areacode): Beta Thanjavur 2554031 04362

S.No Name Area Phone Number


---------------------------------------------------------------------------
1 Alpha Trichy 0431-2554032
2 Beta Thanjavur 04362-2554031

--------------------------------------------------------------------------

Ex.No:6. Programs using string class

Objective:

To study the concepts of string class.

Pre-Lab:

Write a C++ program to convert the string from upper case to lower case
Exercises:

a) Write a function selectionsort() which sorts the strings in the array of string objects, taken as
user input. Test the function in a suitable main program.
Algorithm:
1. In the main() program, declare an array of objects of string class.
2. Get the number of strings and the strings from the user as input
3. Invoke selectionsort() function to sort the array of string objects
4. Display the sorted strings.
Sample input and output:
No. of Strings 5
Enter the strings : eclairs video welcome ecstasy Wellsaid
Sorted output : Wellsaid, eclairs, ecstasy, video, welcome

b) Write a function "no_repetitions(...)" which removes all repetitions of characters in the given
string. Test the function in a suitable main program.
Algorithm:
1. Get the string from the user.
2. Invoke the function no_repetitions() and removes all repetitions of characters from a
string.
3. Display the result.
Sample input and output:
Type in a string: This string contains repeated characters

The string without repetitions is: This trngcoaepd

Ex.No:7. Programs for Data Conversion using Overloading

Objective:

To understand the concept of data conversion using overloading.


Pre-Lab:

Write a C++ program for conversion between C-strings and string objects.
Exercises:
a) Write a C++ program that does data conversion between two user-defined objects. The
program contains two classes class DistFt (for storing distance in feet and inches) and class
DistMtr (for storing distance in meters and centimeters). The classes should contain required
constructors and member functions to perform data conversion between these classes. The
main() function should have necessary statements to demonstrate these conversions.
Algorithm:
1. Declare two classes
a. class DistFt with data members Feet(int) and Inches(int)
b. class DistMtr with data members Mts(int) and Cms(int)
2. Include a constructor and a member function to perform data conversion in class DistFt.
3. main() function should have necessary statements to demonstrate the conversion from
Feet-Inches to Mtr-Cms and vice versa.
4. Display the results.
Sample input and output:
Enter distance in feet, inches : 5 8
Distance in Mtr and Cms is : 1mtr 70cms

Enter distance in Mtr, Cms: 3 65


Distance in feet, inches is : 12 2

Ex.No:8 Programs using operator overloading


Objective:

To understand the concept of operator overloading

Pre-Lab:

Create a class COMPLEX with data members to store real and imaginary parts of a complex
number and with overloaded operators for various operations like addition, subtraction and
multiplication on COMPLEX type objects.
Exercises:

a) Write a C++ program to demonstrate operator overloading and data conversion on polar
coordinates and rectangular coordinates in a 2-dimensional plane. The program should read two
polar coordinates, add them using data conversion and overloaded + operator and display the
result.
Algorithm:
1. Create a class Rectangular with data members X(int) and Y(int)
a. Constructors (i) a default constructor (ii) constructor to convert Polar to
Rectangular
b. Member function to add two rectangular coordinates and return the sum
2. Create a class Polar with data members angle (in radians as int type) and radius (int)
a. Constructors (i) a default constructor (ii) constructor to convert Rectangular to
Polar
b. Member functions (i) functions to read data for Polar object (ii) function to
overload + operator which uses relevant data conversions and calls relevant
member functions and returns the sum (iii) function to display the Polar
coordinates in a formatted manner
3. In the main() program, declare 3 objects of Polar class, read input for 2 objects.
4. Add the given 2 objects and assign the result to the third object using + operator.
5. Display the third object.

Sample input and output:


Radius? 50
Angle in degree ? 60
Radius? 40
Angle in degree? 70

Result
Radius:89.662
Angle:1.1241(64.443 in degree)

b) Write a program to demonstrate overloaded +, - and * operators on MATRIX objects.

Algorithm:

1. Declare class MATRIX that contains data members NoRow (int), NoCol (int) and Mat
(2-dimensional int array)
a. Member functions:
i. to read data members for a MATRIX object
ii. functions for overloading +, - and * operators . These functions should
validate the matrix sizes and display an error message if the operation is
not possible. If valid, return the result.
iii. Function to display a matrix object in a formatted manner
2. Write main() program to declare the required objects to demonstrate all the operations.

Sample input/output:

Enter the input for matrix A:


Number of rows: 4
Number of Cols: 3
Enter the matrix:
155
231
604
123
Enter the input for matrix B:
Number of rows: 4
Number of Cols: 3
Enter the matrix:
232
600
133
444
Sum of Matrices A and B:
387
831
737
567
Difference of the given two matrices A and B:
-1 2 3
-4 3 1
5 -3 1
-3 -2 -1
Product of A and B: Not possible

Ex.No:9 Programs using Inheritance

Objective:

To understand the concept of inheritance.

Pre-Lab:
Simple programs on Inheritance.

Exercises:

a) Imagine a publishing company that markets both book and audio cassettes. Create a class
Publication that has the data members - Title (string) and Price (float). From this class, derive
two classes: class Book, which has the data member Page_Count (int), and class Tape, which has
the data member Playing_time in minutes (int). All the three classes should have a getData()
function to take user input and putData() to display the details. Write the main() program to test
the Book and Tape classes by creating instances of them, asking the user to fill in data with
getData(), and then displaying the data with putData().

Algorithm:
1. Create a class Publication with data members Title (String) and Price (float).
2. Create two derived classes: Book, which data member Page_count (int) and Tape, with
data member Playing_time (int).
3. Define member functions getData() to take user input and putData() to display the details
in all the three classes.
4. Write main() program to test the Book and Tape classes by creating their instances,
asking the user to fill in data with getData() and then displaying the data with putData().
.
Sample input and output:

Enter the No of Details : 2

Enter 1 for book and 2 for tape details : 1


Title: Programming in C++
Page count: 345

Enter 1 for book and 2 for tape details : 2


Tape Name: Fifa
Playing time(min): 70
Price: 100

Title: Programming in C++


Page count: 345

Tape name: Fifa


Playing time: 70
Price: 100

b) Start with the Publication, Book, and Tape classes of Exercise 9a. Add a base class Sales that
holds an array of floats to record the sales of a particular publication. Include a getData( )
function to get three sales amounts from the user, and a putData( ) function to display the sales
figures. Alter the Book and Tape classes so they are derived from both Publication and Sales.
An object of class Book or Tape should input and output sales data along with its other data.
Write a main() function to create a Book-object and a Tape-object and exercise their input/output
capabilities.
Algorithm:
1. Create the class named Publication
2. Include data members - Title (string) and Price (float).
3. Create a class named Sales and include Amt (float) as data member.
4. Create two derived class Book and Tape from publication and Sales
5. Book adds the page count. Tape adds the name and playing time in minutes.
6. All the classes have a getData() to get data from the user and putData() to display the
details
7. Create objects for Book and Tape classes and call the functions.
8. Display the result.
Sample input and output:
Enter the No of Details : 2

Enter 1 for book and 2 for tape details : 1


Title of the book: Programming in C++
Page count: 345.
Sales for publication: 3450

Enter 1 for book and 2 for tape details: 2


Tape Name: Fifa
Playing time(min): 70
Price of the tape: 100
Sales for publication: 3450
Output:
Title: Programming in C++
Page count: 345
Sales amount:3450

Tape name: Fifa


Playing time: 70
Price: 100
Sales amount: 3450

Ex.No:10 Programs using virtual and friend function

Objective:

To study the concepts of virtual function and friend function.

Pre-Lab:
Write a program to find the mean value of a given number using friend function.
Write a program to display base class and derived class messages using virtual function.
Exercises:

a) Create a base class called 'SHAPE' having two data members of type double member function
get-data( ) to initialize base class data members pure virtual member function display-area( ) to
compute and display the area of the geometrical object. Derive two specific classes 'TRIANGLE'
and 'RECTANGLE' from the base class. Using these three classes design a program that will
accept dimension of a triangle / rectangle interactively and display the area.
Algorithm:
1. Create a class named SHAPE
2. Include double member function get-data() to initialize base class data members and pure
virtual function Display_area() to compute and display area of triangle and rectangle.
3. Create two derived classes TRIANGLE AND RECTANGE from the base class SHAPE.
4. Call the functions from the class and display the result.

Sample input and output:


Enter base and height: 2 4
Area of triangle: 4

Enter length and breadth: 2 2


Area of Rectangle: 4

b) Create two classes DM and DB which store the value of distances. DM stores distances in
meters and centimeters and DB in feet and inches. Write a program that read values for the class
objects and add one object of DM with another object of DB. Use a friend function to carry out
the addition operation. The display should be in the format of feet and inches or meters and
centimeters depending on the object on display.

Algorithm:
1. Create two classes - DM and DB.
2. DM stores distances in meters and centimeters
3. DB in feet and inches
4. Add one object of DM with another object of DB
5. Using Friend function, carry out the addition.
6. Display the result.
Sample input and output:
Enter mtr and cm
12 32
Enter feet and inches
6 3
Enter option for output (mtr & cm1 ; feet & inches2)
2
Feet=47 inches =3
1
Feet=14 inches =19

Ex.No:11 Programs using Templates

Objective:

To understand the concept of templates.

Pre-Lab:

Create a function called swaps() that interchanges the values of the two arguments sent to it. Pass
these arguments by reference. Make the function into a template, so that it can be used with all
numeric data types (int, float and double). Write main() program to test the function with various
data types.

Exercises:

a) Create a generic class called GeneralArray which contains an array of any type. Add a
member function that sorts all the elements in the array. In main() function, exercise the class
with arrays of type int, long, double and char.
Algorithm:
1. Create a template class GeneralArray.
2. Include array variable as a data member.
3. Include sort() member function to sort all the elements in the array
4. Call the function from the main to sort the data and display the result.
Sample input and output:
Enter choice for (1)int ,(2) float,(3) double : 1
Enter array size 5
Enter elements:
100
20
120
60
80
Result:
The Sorted order is,
20
60
80
100
120

b) Write a program to explain class template by creating a template T for a class named Pair
having two data members of type T which are input by a constructor and a member function get-
max() return the greatest of two numbers to main.

Note: the value of T depends upon the data type specified during object creation.
Algorithm:
1. Create a template class Pair.
2. Include two Template type data members which are input by a constructor and a member
function get-max().
3. Using get-max() member function, find the greatest of the two numbers.
4. Call functions from the template class and display the result.

Sample input and output:


Enter choice for (1)int ,(2) float,(3) double : 2
Enter numbers: 12.0 13.4
Result: 13.4

Ex.No:12 Programs using Files


Objective:
To understand the concept of programs using files.

Pre-Lab:
Write a C++ program to read and display the contents from a file.

Exercises:

a) A file contains a list of names and telephone numbers in the following form:
Rollno Name dept phoneno Area

Write a C++ program to read the file and output the list in the tabular format. The name should
be left-justified and numbers right-justified. Use a class object to store each set of data and
implement the following task.
i) To determine the student of the specified Roll no.
ii) To determine the name if a telephone number is given.
iii) To update the department whenever there is a change.

Algorithm:
1. Open a file name Stu.txt in write mode and write the student details. The name should be
left-justified and numbers right-justified using manipulators.
2. Open the file Stu.txt in read mode.
3. Using for loop search the student based on the roll no.
4. Using for loop, search for a student based on the given telephone number
5. Using for loop and branching statements, update the department whenever there is a
change.
Sample input and output:
Enter the student details:
No of student: 2
Rollno : 1
Name : Alpha
Dept : ICT
Phoneno : 9994080020
Area : Thanjavur

Rollno : 2
Name : Beta
Dept : IT
Phoneno : 8224080020
Area : Trichy

SEARCHING:
Enter the Roll no : 1
Name of the student is Alpha

Enter the phone number: 9994080021


Not in data base.

Enter the student name and dept for update:


Alpha
IT
Updated.
Ex.No:13. Dividing Large Program into Multiple Files

Objective:

To understand the concept of dividing large program into multiple files.

Exercises:

a) Write a program which has class EmpDetails that contains a function to get employee details
(FileA)
b) Write a program which has class Salary that contains a function to calculate netsalary of an
employee based on the details given in FileA (FileB)
c) Write a program which will call the function to display the employee details from FileB.

Algorithm:
1. Split the program into three separate programs.
FileA: Contains the base class EmpDetails.
FileB: Contains the derived class Salary
FileC: Contains the main program that contains member functions to calculate the salary and
display the employee details. Include FileA and FileB as header files in this program.
2. Execute FileC and display the result.

Scenario Based Exercise

Develop a voting system for election. It allows the user to put the vote for five candidates in a
local election. So it shows the name of the candidate in the user interface and then the user
selects the candidate. Based on the vote given by the user, it calculates the number of votes
received by each candidate. The program should then output each candidate's name, the number
of votes received, and the percentage of the total votes received by the candidate. Your program
should also output the winner of the election.

A sample output is:

Candidate Votes Received % of Total Votes


Johnson____5000___________25.91
Miller______4000___________20.73
Duffy______6000___________31.09
Robinson___2500___________12.95
Ashtony____1800___________9.33
Total______19300

The Winner of the Election is Duffy.


The following concept needs to be implementing in coding:
* OOP Class, Objects,
* Constructor,
* Destructor
* Inheritance,
* Polymorphism
* Array of objects
* Class Collaboration

ADDITIONAL EXERCISES:

1)Write a function called reverseIt() that reverses a C-string (an array of characters). Use for loop
that swaps that first and last character, then the second and next next-to-last characters, and so
on. The strings should be passed to reverseIt() as an argument. Write program to exercise
reverseIt(). The program should get a string from the user, call reverseIt(), and printout the result.
Use an input method that allows embedded blanks. Test the program with Napoleons famous
phrase, Able was I ere I saw Elba.

2) Create a class Distance containing the data members feet, inches and a const member MTF
(Meter To Feet) which assigned a constant value 3.280833F. Create overloaded constructors:
default, single parameter (takes meter as input and converts it into feet and inches), and 2
parameters (feet and inches). Class should have the following member functions: getDistance(),
showDistance() and a conversion operator for basic to user-defined and user-defined to basic.

3) Write a program that emulates the DOS COPYcommand. That is, it should copy the contents
of a text file (such as any .CPP file) to another file. Invoke the program with two command-line
argumentsthe source file and the destination filelike this: C>copy srcfile.cpp destfile.cpp. In
the program, check that the user has typed the correct number of command-line arguments, and
that the files specified can be opened.

4) Imagine tollbooth at a bridge. Cars passing by the booth or expected to pay a 50 cent toll.
Mostly they do, but sometimes a car goes by without paying. The tollbooth keeps track of the
number of cars that have gone by, and of the total amount of money collected. Model this
tollbooth with a class called TollBooth. The two data items are a type unsigned int to hold the
total number of cars, and a type double to hold the total amount of money collected. A
constructor initializes both of this to zero. A member function called payingCar() increments the
car total and adds 0.50 to the cash total. Another function, called nopayCar() increments the car
total but adds nothing to the cash total. Finally, a member function called display() displays the
two totals. Make appropriate member functions const. Include a program to test this class. This
program should allow the user to push one key to count a paying car, and another to count a non-
paying car. Pressing the ESC key should cause the program to printout the total cars and total
cash and then exit.
5)Write a C++ program to create a class called COMPLEX and implement the following
overloading functions ADD that return a COMPLEX number. I. ADD (a, s2) - where a is an
integer (real part) and s2 is a complex number. II. ADD (s1, s2)-where s1 & s2 are complex
numbers.

6)Program: Write a C++ Program to display names, roll nos, and grades of 3 students who have
appeared in the examination. Declare the class of name, roll nos and grade. Create an array of
class objects. Read and display the contents of the array.

7) Write a C++ program to count the number of persons inside a bank, by increasing count
whenever a person enters a bank, using an increment(++) operator overloading function, and
decrease the count whenever a person leaves the bank using a decrement(--) operator
overloading function inside a class.

8)Create a class rational which represents a numerical value by two double values-
NUMERATOR & DENOMINATOR. Include the following public member functions:
Constructor with no arguments (default).
Constructor with two arguments.
Reduce() reduces the rational number by eliminating th highest common factor between the
numerator and denominator.
Overload + operator to add two rational number.
Overload >> operator to enable input through cin.
Overload << operator to enable output through cout.
Write a mian() to test all the functions in the class.

9)A hospital wants to create a database regarding its indoor patients. The information to store
include
a) Name of the patient
b) Date of admission
c) Disease
d) Date of discharge

10)Create a structure to store the date(year,month and date as its members). Create a base class
to store the above information. The member function should include functions to enter
information and display a list of all he patients in the database. Create a derived class to store the
age of the patients. List the information about all the pediatric patients (less than twelve years in
age).

11)Make a class Employee with a name and salary. Make a class manager inherit from
Employee. Add an instance variable, named department, of type string. Supply a method to
string that prints the managers name, department and salary. Make a class Executive inherit
from manager. Supply a method to string that prints the string that prints the string Executive
followed by the information stored in the manager superclass object. Supply a test program that
tests these classes and methods.

12) Create a 'DISTANCE' class with :


- feet and inches as data members
- member function to input distance
- member function to output distance
- member function to add two distance objects
Write a main function to create objects of DISTANCE class. Input two distances and
output the sum.

13) Create a 'STRING' class which overloads = = ' operator to compare two STRING objects.

14) Write a program that calculates how much money youll end up with if you invest an amount
of money at a fixed interest rate, compounded yearly. Have the user furnish the initial amount,
the number of years, and the yearly interest rate in percent. Some interaction with the program
might look like this:

Enter initial amount : 3000

Enter number of years: 10

Enter interest rate: 5.5


At the end of 10 years, you will have 5124.43 dollars.

15) Create a class called bMoney. It should store money amounts as a long double. Use the
function mstold() to convert a money string entered as input into a long double, and the function
idtoms() to convert the long double to a money string for display. You can call the input and
output member functions getmoney() and putmoney(). Write another member function that adds
two bMoney amounts; you can call it madd(). Adding bMoney object is easy: Just add the long
double member data amounts in two bMoney objects. Write a main() program that repeatedly
requests the user to enter two money strings, and then displays the sum as a money string.

S-ar putea să vă placă și