LAB MANUAL
CS102 Object Oriented Programming using C++
Implementation Implementation of C++ programming programming problems Aim:
M ain aim aim of this course course is to understand understand and solve logical logical & mat hemat ical ical problems throu gh C++ language language . Stre Stre ngthen know ledge of a p rocedural p rogramm ing language. language. Desig Designn and develop solut ions to in term ediate level problem s using the C language. language. Furth er develop your skills skills in in soft w are developm ent u sing sing a procedural language. language.
Objectives: The ob jective of th is course is is to offe r the m odern program m ing language language C++ that shall help the students to im plement the various various concept concept o f ob ject ject orientation p ractical ractically. ly. The students w ill ill be able to programm e in the object oriented technology with t he usag usagee of C++. ++. This This course will also prepare students with the necessary programming background f or Data Str uctu res using using C/ C/ C++ and Java Java pro gram m ing co co urses.
DESCRIPTION OF SCHEDULE: W eek Week 1
Practical List List 1. Write a C++ C ++ program to display "Hello Computer" on the scr een. 2. Write a C++ C ++ program to display Your Name, Address a nd City in different lines 3. Write a C++ program to find the area of a c ircle using the formula: Area = PI * r2 4. Write a C++ program to find the area a nd volume of sphere. Formulas are: Area = 4*PI*R*R Volume = 4 /3*PI*R*R*R. /3*PI*R*R*R. 5. Write a C++ C ++ program to print the multiply value of two a ccepted numbers 6. Write a C++ program to convert centigrade into Fahrenheit. Formula: C= (F-32)/1.8. 7. Write an C++ C ++ program that declares 5 integers, determines and p rints the largest
and smallest in the group. . 8. Write an C++ program that declares two integers, determines whether the first is a multiple of the second and print the result. [ Hint : Use the remainder operator.] 9. Write an C++ program that declares two integers, determines whether the first is a multiple of the second and print the result. [ Hint : Use the remainder operator.]
Week 2
Classes & Objects Specifying a class, creating class objects, accessing class members, access specifiers: public, private, and protected, classes, objects and memory, static members, the const keyword and classes, the static objects, empty classes, nested classes, local classes, abstract classes
List of programs: 1. Write a program in C++ to display your name, Branch, Year on too the computer screen without using classes and object. All information should be displayed in the separate line. 2. Write a menu driven program in C++ to perform all basic arithmetic operation addition, subtraction, multiplication, and division of two given values. Program receives two values and required operation to be performed from the keyboard and display particular result of the required operation. 3. Write a menu driven program in C++ that receives 4 digit integer value the keyboard and perform following operations (a) Reverse of that no. (b) sum of number with it’s reverse (c). sum of alternative digits(1 digit+3 digit and 2 digit+4 digit) 4. Write a menu driven program in C++ to receive integer number and convert equivalent binary, octal, hexadecimal number. 5. Write a menu driven program in C++ to perform all basic arithmetic operation addition, subtraction, multiplication, and division of two given values using function and switch case. Program receives two values and required operation to be performed from the keyboard and display particular result of the required operation. 6. Write a program in C++ to display mark sheet. Of the student. Define a class that contains data members to store student information line name, Branch, semester, marks in 6 different subjects, etc. Declare some member functions to get these information from the key board, to calculate result and to display all gathered information on to the computer screen in proper format. 7. Define a class employee. Include the following members: Data Members: a. Name of the employee b. Age of the employee Member Functions: a. To get the name and age of the employee
b. To display the name and age of the employee. 9. Define a class BankAccount to represent a bank account. Include the Following members: Data Members: 1. Name of the depositor 2. Account Number 3. Type of account 4. Balance amount in the account Member Functions: 1. To assign initial value 2. To deposit an amount 3. To withdraw an amount after checking 10. Define a class employee having data members as emp_code, dept_code, age, basic, DA, HRA and three member functions as getdata(), putdata(), calculatesalary() to get, display all the values of data members and calculate the total salary by adding basic, DA, HRA. Write this program for 10(ten) employees using an array of objects. */ Week 3
BANKIN G O PERATION USING CLASS AN D OBJECTS Algorithm Step 1 : Create an ob ject b of th e class bank account . Step 2: Read th e num ber of r ecords. Step 3: call the init m emb er function of t he class bank account t hrough th e object created. Step 4 : Assign 500 to the b alance in t he record s. Step 5: Display a menu w ith th e follow ing options create d eposit w ithdraw display. Step 6: Read t he choice. Step 7: If the cho ice is create th en call the create m emb er fun ction using the ob ject. Step 8: prom pt and read the user’s name, account num ber and account type f or all the n records. Step 9: If t he choice is deposit call the deposit m emb er function u sing the f unction. Step 10: Read the accoun t nu m ber. Step 11: Check w het her t his account num ber is already exiting in th e list. If true Step 12: Read t he amoun t t o b e deposited. Step 13: Update the balance by adding th e amo unt deposited to the balance.
Step 14 : Display t he ba lance. Step 15: If th e choice is withd raw, call the w ithdraw mem ber fu nction. Using object Step 16: Read the accoun t nu mb er. Step 17: If the account num ber existing in t he list t hen . Step 18: Read t he amount to b e withd rawn . Step 19: Retrieve the am ount from balance. Step 20: If th e balance is less than 500 t hen Step 21: Calculate balance + w ithd raw am oun t-500. Step 22: Assign 500 to th e balance. Step 23: Display the w ithdrawn am ount . Step 24: If th e choice is display, invo ke th e display m em ber fun ction u sing the Object. Step 25: Read th e account num ber. Step 26: If th is accoun t nu m ber is existin g in the list th en. Step 27: Display th e details such as nam e, accoun t numb er, accoun t typ e and balance in th e given account num ber. Week 4
INV ENTO RY OF BOOK USING CON STRUCTOR AN D DESTRUCTOR Algorithm Step 1 : Create an object fo r th e class boo k. Step 2: Declare t he point er variable for author, title, and pu blisher and the Variable for price and stock po sition. Step 3: Read the n um ber of records. Step 4:Display a m enu w ith th e fo llow ing choice create ,buyboo k, tran saction and display. Step 5:Using sw itch case execute t he stat em ents correspond ing to th e choice. Step 6:If th e choice is create, read the tit le, aut hor , pub lishes, price and stock
position and pass it to the constructor of the book class. Step 7;Find t he string length of each of th e po inter variables dynamically. Step 8:If t he choice is b uy boo ks, read th e t itle, auth or, stock fro m th e user and check these with the array already created. Step 9:If th e auth or n ame and t itle m atches then display th e m essage” :Available” and read the number of copies. Step 10:Decrement the stock position by 1 and display the moun t to be paid. Increm ent successful transaction by 1. Else display “ NOT success” and incremen t the unsuccessful tran saction by 1. Step 11:If th e tra nsaction ; display unsuccessful transaction.
th e
variables, successful
tran saction
and
Step 12:If th e ch oice is display, th en display all th e d etails such as title, auth or, price, pub lishes and sto ck po sition . Week 5
STUDENT EVALUTION USING INHERITANCE Aim To w rite a C++ program fo r student s evaluation concept using inherit ance. Algorithm Step 1: create a class stud entp ersonal declare roll n o,age,name,sex in p rotect ed m ode. Step 2: U sing a param eterized constructo r initialize th e values for all th e data m emb ers. Step 3: Create ano th er class studentm ark th at is inhe rited f rom th e base class and having th e data m emb ers m ark1,mark2,m ark3,mark4 Using a parameter ized constructor init ialize th e value for mark1,mark2,m ark3,mark4. Step 4 : Create anot her class called student spor ts and declare score as protect ed m ode. Step 5: Create a class student result and p ublic inherit ed fo rm stu dent m arks and studen tsport s having the data m em bers total,avg,grade.. Step 6 : Calculate t he t ota l and avg and display th e result. Week 6
1. Create a class called Employee that includes three pieces of information as instance variables – a first name (type String), a last name (type String) and a monthly salary
(double) 2. Create a constructor in above class to initialize the three instance variables. Provide
a get method for each instance variable.. 3. Create two employee objects and d isplay each object’s yearly salary. 4. Give each employee a 10% raise and display each Employee’s yearly salary again.. 5. Write C++ program to create five object of book, get information of book using getdata() function including name, price, publication and author. 6. Write search() function to search a specified book, if book is search return the complete information of book and print the information of book using putdata()
function.
Week 7
TO READ A VALUE OF DISTANCE FROM ONE OBJECT AND ADD WITH A VALUE IN ANOTHER OBJECT USING FRIEND FUNCTION Aim To read a value of distance from one ob ject and add w ith a value in anoth er object using friend function. Algorithm Step 1 : Create tw o classes AB and AC and store t he value o f distances. Step 2 : Declare friend fu nction . Step 3 : Read th e value from th e classes. Step 4 : Perform addition to add o ne object of AB with anot her object of AC. Step 5 : Display the result of add ition . Week 8
M ATRIX OPERATION U SING OPERATOR OVERLOAD ING A im To create a C++ program for perform ing matrix op erations using operator overloading. Algorithm Step 1: Create 3 object fo r th e mat rix class m1 , m2, m 3. Step 2: Read th e element s of th e m atrix A and mat rix B using th e getdat a function in t he m atrix class, which is invoked b y t h e o b j e ct m 1 a n d m 2 . Step 3: Invoked the op erator function fo r m atrix addition using the statement m3=m1.operator+(m2). Step 4: Create an ob ject c o f th e type m atrix. Step 5: Calculate m atrix addition of the m atrices of m 1 and m 2 and
Stor e it in th e object c return c. Step 6: Display the resultant m atrix using the d isplay mem ber Function of mat rix by invoking through t he object m 3. Step 7: Call the operator function fo r m atrix subtraction using the St a t e m e n t m 3 = m 1 - m 2 . Step 8: Pass the object m 1 and m 2 to the o perator function. Step 9: Create an object of type m atrix. Step 10: Calculate mat rix sub traction u sing the object m 1 and m2 and store in th e object created return c. Step 11: Invoke th e display function using th e object m 3. Step 12: Call th e operato r function for m atrix m ultiplication using t h e st a t e m e n t m 3 = m 1 * m 2 . Step 13: Create an object o f type m atrix. Step 14: Perform the m atrix mult iplication and store it in t he object and return it. Step 15: Invoke th e display function u sing the ob ject m 3. Week 9
AREA CALCULATION USING V IRTUAL FUN CTIONS A im To create a C++ pro gram for calculating the ar ea using th e virtual function. Algorithm Step 1: Create a class shape con taining 2 m em bers function and d isplay area , w hich is virtu al. Step 2: Create th e ob ject fo r t he classes circle, rectangle and triangle. Step 3 : Overload op erator << to d isplay the r esults of addit ion and subtraction op erations on t w o p olynomials. Step 4: Disp lay the r esults.
W eek 10
Polymorph ism Lab Objectives
To gain experience with
W eek 11
describing the information contained within a class hierarchy the concept of a polymorphic variable and its relationship to class hierarchies the interaction between polymorphism and memory management how to distinguish between virtual and non-virtual overriding the concept of downcasting multiple inheritance designing and using software frameworks
1. Write a C++ program in which you are overloading all arithmetic operators. 2. Overload [] operator. 3. Write a program that accepts two values either integer or double . Design functions that understand the input, add them and p rovide the correct output. 4. Create a base class called shape. Use this class to store t wo double type values that could be used to compute the area of figures. Derive two specific classes called triangle and rectangle from the base shape. Add to base class, a member function get_data() to initialize base class data members and another member functions
display_area() to compute and display the area of f igures. Mark the display_area() as avirtual function and redefine this function in the derived class to suit their
requirments.(Use pure virtual function) 5. Write a program in C++ to demonstrate default constructor. Create a class having two data members in the private section. Define a default constructor to initialize these data members to initial value and display these values with the help of member function 6. Write a program in C++ to demonstrate parameterized/constructor overloading constructor. Create a class calculator that contains four data members in it. Initialize data members with different values using parameterized constructor and perform various arithmetic operation over these values and display result on to the computer screen. 7. Create a class called Triangle that stores the length of the base and height of a right triangle in two private instance variables. Include a constructor that s ets these values. Define two functions. The first is h ypot( ), which returns the length of the hypotenuse. The second is area( ), which returns the area of the triangle.
W eek 12
1. Create a base class that contains a function display(), displaying “I am in base” . Function with same name display() is in derived class ,displaying “I am in derive”. 2. Write a C program that manipulates the above text file. T he program must implements the operation to modify a record, delete a record and append new records. 3. Write C++ p rograms for the following operation to work like DOS Co mmands: a. create a test1.txt file nd b. copy test1.txt data into 2 file name test 2. txt c. compare test1.txt and test2.txt e. concatenate test1.txt and test2.txt into test3.txt and display the data
4. Write a C program to open two files containing integers (in sorted order) and merge their contents.
W eek 13
Operator Overloading and Type conversion Defining operator overloading, rules for overloading operators, overloading of unary operators and various binary operators, overloading of new and delete operators, type conversion - basic type to class type, class type to basic type, class type to another class type.
List of programs: 1. Declare a class Number that contains two data member value1 and value2 of the type of integer, define constructor to give initial value, and perform addition , subtraction, multiplication and division of these two numbers using operating overloading of +,-,*,/ operator respectively [hint- binary operator overloading using member function]
2. Declare a class Number1 that contains two data member value1 and value2 of the type of integer, define constructor to give initial value, and perform addition, subtraction, multiplication and division of these two numbers using operating overloading of +,-,*,/ operator respectively [hint- binary operator overloading using friend function]
3. Declare a class Number3 that contains a data member value of the type of integer, define constructor to give initial value, and perform unary minus ,increment and decrement this number using operating overloading of ,++,-- operator respectively [hint- Unary operator overloading using member function] 4. Declare a class Number3 that contains a data member value of the type of integer, define constructor to give initial value, and perform unary minus, increment and decrement this number using operating overloading of -,++,- operator respectively [hint- Unary operator overloading using friend function] 5. Define a class complex that contains two data member to store real and imaginary part of the complex number. Create a function to get values from the keyboard into these complex numbers, overload binary + and – to calculate addition and subtraction of two complex numbers respectively using member function . 6. Write a program to demonstrate explicit type conversion from basic type to user defined data type. 7. Write a program to demonstrate explicit type conversion from User Defined data type to Basic data type data type. 8. Write a program to demonstrate explicit type conversion from one user defined data type to another user defined data type. 9. Write a program in C++ to calculate mean value of n numbers using friend function. 10. Write a program in C++ to find greater between two numbers using friend function. 11 Write a program in C++ to display student’s information using friend function. 12 Write a program in C++ to swap between two numbers using friend function.
W eek 14
Inheritance Introduction, defining derived classes, forms of inheritance, ambiguity in multiple and multi-path inheritance, virtual base class, overriding member functions, order of execution of constructors and destructors . Create a class A with some private data members and some public member function, now create a derived class B, that inherits A and having some data members and member functions it’s own, in main( ) function access attributes of base class with the help of derived class object to show inheritance concepts. 2. Create a class publication which has title of book and writers name. create another class sales which accounts no. of sales for every month (upto 3 months) and then calculate total sales. Write a program to solve the ambiguity problem in inheritance where two different classes are inherited from single base class and a new class is derived from these two derived classes. How this problem is solved with the help of virtual base class concept.
W eek 15
Virtual functions & Polymorphism Concept of binding - early binding and late binding, virtual functions, pure virtual functions, virtual destructors & polymorphism .
1. WAP to use ‘this’ pointer to find elder from two person. Define a class Person to store age of the person. Define constructor/member function to give initial value to the data member age. And then define a function elder to compare ages of two different person using this pointer to find out the elder person. 2. WAP a program to show how member of the class are accessed through the pointer to class using arrow operator (->). 3. Write a program to show the concept of virtual function with the help of suitable programming example. 4. Create a simple “shape” hierarchy: a base class called Shape and derived classes called Circle, Square, and Triangle. In the base class, make a virtual function called draw( ),and override this in the derived classes. Make an array of pointers to Shape objects that you create on the heap (and thus perform upcasting of the pointers), and call draw( ) through the base-class pointers, to verify the behavior of the virtual function. If your debugger supports it, single-step through the code. 5. Modify Exercise 5 so draw( ) is a pure virtual function. Try creating an object of typeShape. Try to call the pure virtual function inside the constructor and see what happens. Leaving it as a pure virtual, give draw( ) a definition. 6. Write a small program to show the difference between calling a virtual function inside a normal member function and calling a virtual function
inside a constructor. The program should prove that the two calls produce different results. W eek 16
Exception handling Aim of the program 1. Create a class with a main( ) that throws an object of class Exception inside a try block. Give the constructor for Exception a String argument. Catch the exception inside a catch clause and print the String argument. Add a finally clause and print a message to prove you were there.
2. Create your own exception class using the extends keyword. Write a constructor for this class that takes a String argument and stores it inside the object with a String reference. Write a method that prints out the stored String. Create a trycatch clause to exercise your new exception. 3. Write a class with a method that throws an exception of the type created in Exercise 2. Try compiling it without an exception specification to see what the compiler says. Add the appropriate exception specification. Try out your class and its exception inside a try-catch clause. 4. Define an object reference and initialize it to null. Try to call a method through this reference. Now wrap the code in a try-catch clause to catch the exception. 5. Create a class with two methods, f( ) and g( ). In g( ), throw an exception of a new type that you define. In f( ), call g( ), catch its exception and, in the catch clause, throw a different exception (of a second type that you define). Test your code in main( ). 6 . Repeat the previous exercise, but inside the catch clause, wrap g( )’s
exception in aRuntimeException. W eek 17
Learning Outcomes: On completion of this module, the learner should be able to: Describe the syntax and semantics of the C++ programming language Explain the use of class and object. Work in a team to analyze engineering problems and develop C++ programs for solving these problems; Use the basic utilities and facilities for software development . debug and test software;
Develop a minor software in C++ language