Practice Exercise for object Oriented programming in C++, Exercises of Object Oriented Programming

Practice Exercise for object Oriented programming in C++. Solve the exercise and become Master in C++.

Typology: Exercises

2021/2022

Available from 05/01/2023

MnGhani
MnGhani 🇵🇰

6 documents

1 / 22

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Practice Questions for Object Oriented Programming in C++
Question#1
Basic Input , Output, Arithmetic Operations and Assignment
Q.1 Write a program that reads a number N and print all its divisors.
Q.2 Write a program for computing the difference of the digits of any given number
Q.3 Write a program to compute the sum of square of integers from 1 to 20.
Q.4 Write a program that takes a floating point number from user and prints an integral
value after applying floor function. For example the if floating point number is from 1.1 to
1.9 then after applying ceiling function will be 1.
Question#2
Advanced Arithmetic Operations , if else statement and switch
statement
Q.1 Write a program that takes input for two sides of right angled triangle from user. Use
Pythagoras theorem to calculate third side.
Output will be:
Enter first side
3
Enter second side
4
The length of three sides is:
First: 3
Second: 4
Third: 5
Q.2 Fibonacci series is a series in which next number is obtained by adding two previous
numbers. Write a program that prints the series up to the limit specified by the user.
Q.3 Write a program that take income of twelve months of year of a person from the
user. A person earns different money each month. Add 12 months salary and print
average salary in end
Output will be:
Enter first month income
$10
.
.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

Partial preview of the text

Download Practice Exercise for object Oriented programming in C++ and more Exercises Object Oriented Programming in PDF only on Docsity!

Practice Questions for Object Oriented Programming in C++

Question# 1

Basic Input , Output, Arithmetic Operations and Assignment

Q. 1 Write a program that reads a number N and print all its divisors. Q. 2 Write a program for computing the difference of the digits of any given number Q. 3 Write a program to compute the sum of square of integers from 1 to 20. Q. 4 Write a program that takes a floating point number from user and prints an integral value after applying floor function. For example the if floating point number is from 1.1 to 1.9 then after applying ceiling function will be 1.

Question#

Advanced Arithmetic Operations , if else statement and switch

statement

Q. 1 Write a program that takes input for two sides of right angled triangle from user. Use

Pythagoras theorem to calculate third side. Output will be: Enter first side 3 Enter second side 4 The length of three sides is: First: 3 Second: 4 Third: 5 Q. 2 Fibonacci series is a series in which next number is obtained by adding two previous numbers. Write a program that prints the series up to the limit specified by the user. Q. 3 Write a program that take income of twelve months of year of a person from the user. A person earns different money each month. Add 12 months salary and print average salary in end Output will be: Enter first month income $ 10 . .

Enter Twelve month income $ 20 Average Salary of person 1 is 3. Repeat this process for 5 person. Q. 4 Write a program that take input an integer from user, calculate its factorial and then print its factorial. Q. 5 Write a program that prints sum of odd integers between 1 and 50. Q. 6 Write a program that takes two integers as input. The second number will be the power of first one. Output will be: Enter first integer 2 Enter power of this integer 3 The result is: 8 Q. 7 Take two numbers from the user and then divide the greater number by smaller one. Output will be: Divisor= Dividend= Remainder= Quotient= Repeat this process for at least one time up to any sentinel value. Q. 8 Take a number from user as the maximum upper limit and then print all those numbers from 2 to that limit that are prime.

Question# 3

Functions

Q. 1 Raising a number n to a power p is the same as multiplying n by itself p times. Write a function called power that take a double value for n and an int value for p, and return the double value. Write main function that gets value form user to test the function Q. 2 Write a functions rectarea to calculate the area of rectangle. It should take an argument of type float and return an argument of the same type. Write a main program that gets a base and height value form the user and call rectarea.

Q. 4 Write a recursive function power that calculates the power of given number. The data type for power/exponent will be integer and for base it will be double. The prototype for recursive function will be: double power (double base, int exponent); Write sample main function for calling your own defined function with base =2 and exponent = 4 For example cout << power (2, 4); will print 16. Q. 5 Write a function that receives a floating point number and returns an integral value after applying ceiling function. For example the if floating point number is from 1.1 to 1.9 then after applying ceiling function will be 2. Q. 6 Write a function findminimum that takes two parameters. The data type for both will be long. The function will return maximum of two values. Then write a main program that takes two values from user and passes these values to function findminimum and prints the maximum of two. Output will be: Enter first number 123 Enter second number 2 The minimum number is 2

Question # 5

Arrays (One dimensional and Multidimensional)

Q. 1 Write a program that declares an array of size 10 in main. The array will be initialized by taking input from user. The values in array will be used to draw a histogram. For example if the values in array are like this: 0 1 2 3 4 5 6 7 8 9 3 5 10 7 6 2 0 4 13 8 The output will be:

**

Q.2 Write a function convertdec for converting a decimal number to binary number. The function will receive the number as parameter and will print its binary representation. The data type for the number will be long. User will input the number in main and will pass the number to function convertdec. Q. 9 Make a logical calculator that performs the following functionality

  1. OR two binary numbers.
  2. AND two binary numbers.
  3. Quit. First take input from user number from 0 to 3 and then take two binary numbers from user. And perform required operation specified by number entered. Use switch structure for this question. Also write two functions for each of logical operation. Q.3 A mining company pays its miners on commission basis. The miners receive $200 per week plus 9 percent of their cost of coal they mined. For example a miners who mined coal of amount $5000 in mining in a week receives $200 plus 9 percent of $5000 or a total of $650. The total no of miners in company is 200. Write a program that first takes cost of coal they mined of every miners in an array and determine how many of the miners earned salaries in each of the following ranges. Grade1 $200-$ 499 Grade2 $600-$ Grade3 $1000-$ 3000 Grade4 $ 3 001 or above And then calculate average of salaries in every grade level. The output will be:

Grade1 Grade2 Grade3 Grade

1 $ 2 $630 …… 3 $530 …… . 200 Total 2 1 miners Total $980 $ Salaries Average $490 $ Q. 4 Write a main that declares a string in c++. Then write a function that receives this string as pointer. The function will declare another string. Then take a string from user to

use any variable for traversing the array. Apply direct arithmetic on pointer variable. Then print the height for cities entered using for loop. For example height of city can be 2291m.

Question # 8

Structures

Q.1 Write a short program that will: a. Create structure to hold a data of a Employee including Name, CNIC, Age. b. In main create an array of 50 students and pass it in function studentinfo. c. Write a function studentinfo that receives an array of students of size 50 and that first takes input in this array and then print this information. The output will be: Enter name of student ABC Enter CNIC of student 35202 - 2514707 Enter Age of student 36 . . CNIC Name Age 35202 - 2514707 ABC 36 . . .

Revision of All topics Covered

Q. 1 Write a program that prints the Counting 0 to 9 in the following format: 0 11 222 3333 Up to 9 , which is printed 9 times. Note: Use ASCII code for numbers.

Q. 2 Write a function getplural that receives a string from main and then take input of

nouns from user and returns their plurals on the basis of these rules: a. If noun ends in ” y„ remove ” y„ and add „ies.„ b. If noun ends in „s„, ” ch„, or ” sh„ and ” es.„ c. In all other case, just add ” s.„ The main will call the function and will display the plural of the noun. Note: The size of the string will be such that nouns of maximum length can be input. Output: Enter a noun: student

The plural of student is students

Q. 3 Write a main program that adds two 4 * 4 square matrix and then display in matrix

format. Use arrays for storing two matrix and resultant matrix. Also pointer notation should be used for all manipulation. Initialize two matrixes used in addition at the time of declaration.

Q. 4 Write a short program that will:

a. Create structure to hold a data of a phone set including, inventory number that is time of entry of phone set in inventory, model number, color, brand name, and category. b. In main create an array of phone set of size 10 and pass it in function orderedinfo. c. Write a function orderedinfo that takes an array of phone set of size 10 and that first sorts on the basis of inventory number and then print the category and all other information of the phone set in the following form: Output: Catogory model_number Inventory_number color Brand_name Basic 1200 12:38 red Panasonic ….

Question # 8

  1. C++ stores list of values and tables in ______________________.
  2. The element of an array are related by the fact that they _____________________.
  3. When referring to an array element, the positioned number contained within square brackets is called a ______________________.
  4. The names of the four elements of array p are ______________________.
  5. Naming an array, stating its type and specifying the number of elements in the array is called ______________________.
  6. The process of placing the elements of an array into either ascending or descending order is called ______________________.
  7. In double-subscripted array, the first subscript identifies the _______________of an element, and second subscript identifies the ________________ of an element.
  8. The name of the element in row 3 and column 5 of the array d is ______________________.
  9. All programs can be written in terms of three types of control structures: ______________________.
  10. Repeating a set of instructions a specified number of times is called ______________________.
  11. When it is not known in advance how many times a statement will be repeated, a ______________________ value can be used to terminate the repetition.
  12. The ______________________ program combines the output of the compiler with various library functions to produce executable image.

return 1 otherwise 0. Iterate string as individual characters using loop. The ending condition will be null character.

Question # 10

By value, By reference, Function Overloading, Default arguments

Q. 1 Write a complete C++ program with two alternate functions specified below that each simply triple the variable count defined in main. Then compare and contrast the two approaches. These two functions are a) Function triplecallbyvalue that passes a copy of count call-by value, triples the copy, and returns value. b) Function triplebyreference that passes count with true call by reference via reference parameter, and triples the original copy of count through its alias Q. 2 Write a short program that will: d. Create structure to hold a data of a Person including Name, Age and Address e. Write a function personinfo that receive reference of one structure variable of type Person. It takes input for its members and displays it. f. In main call the function personinfo ( struct Person&). Q. 3 Write a function that calculates volume of box and returns it to calling program. The prototype of function is given below: int boxvolume (int length =1, int width =1, int height =1 ); a) Call this function using no argument, 1, 2,3 argument. b) Try for combination when you want to change only second argument. Q. 4 Raising a number n to a power p is the same as multiplying n by itself p times. Write a function namely power that take two arguments, the second argument will be int in all cases. Create a series of function with the same name that works for all types double, int, char, float long. Write a main() program that exercise these overloaded functions with all arguments.

Question # 11

Constructors and member functions

Q. 1 Create a class called time. Its three members, all type int, should be called hours, minutes and seconds. It should also have an appropriate default constructor and following functions:

1. time ( int hrs, int min, int sec) Store these values in class data members. 2. time ( int sec) Convert and store it in class data members. Takes sec and covert it in the hours, minutes and seconds and then store it.

  1. time Addtime ( time tm1, time tm2) Add will convert each one to seconds (type int), add these quantities, converts this result back to hours, minutes and seconds stores the result in a variable and return it. Use utility functions for conversions. Write two utility functions. Make sure tm1 and tm2 will be used for read only purpose.
  2. int timetosec ( time tm1) Take time and convert it into seconds.
  3. time sectotime ( int sec) Takes sec and covert it in the hours, minutes and seconds and return it.
  4. void display ( ) Display will display the time in format 12:59:59.
  5. void takeinput () This will take time in the format 12:59:59 and will store it in hours, minutes and seconds. Q. 2 A main ( ) program should create two initialized time objects. Then it should add the two initialized values together, leaving the result in the third time variable. Finally it should display the value of third time variable. Write a class namely student. Write the header of the class that includes data members and member functions of the class. The data members of the class are Rollno, name, marks1, marks2, and marks3.Use appropriate data types for all data members. Write wrapper functions for first two data members only. Write a public member function getgpa that will call a utility function namely calculategpa internally. The return type of getgpa will be float. In calculategpa use 3 data members marks1, marks2, marks3 and calculate gpa. Write appropriate constructors for this class. Use both approaches for constructors. First write with constructors with default values and second with overloaded constructors. Note : Write class header and implementation separately in same .cpp file.

Question # 12

Constructors, Destructors and Wrapper Functions

Q. 1 Create an labour class for labours in factory:

  1. The member data should comprise an int for storing the labour number (the labour number should not be changeable after initialization) char array for name, a float for storing labour salary.
  2. Salary should be in range 3000-20000. Use helper function for salary validation.
  3. Write appropriate constructors, wrapper functions and destructors. Only one constructor is allowed for all options.
  4. Write a function that increments salary of labour.
  5. Write main that initializes an array of labour and displays all data.

Member function Object non-const non-const non-const const const non-const const const

Question # 14

Operator Overloading

Q. 1 Create a class Complex to store and manipulate a Complex Number. It should be able to store Real and Imaginary portions as double , and provide appropriate functionality to correctly execute the following main( ). Comments at the end of each line refer to the Explanation Notes on next page. void main() { Complex c1( 3.0 ); //E Complex c2 = c1 + 4.5; //E02, E Complex c3; //E cin >> c3; //E c1 = c1 + 1.2 + c3 – (c1 – 7.5 – c3); //E05, E08, E cout << “The value of c1 is:” << c1 << endl; //E c2 = c3 = ((c1 > 20.5)? c1 : 20.5); //E05, E12, E cout << c2 << “, ” << c3; //E cin >> c1 >> c2 >> c3; //E if (c1 > c2 && c1 >= c3 || c2 == c3) //E12, E { Complex c4(3.5, 2.1); //E cout << c4 << endl; //E } else if (c2 == c3) //E { Complex c4 = c1 += c2 - = c3; //E02, E09, E cout << “Last value is:”<< c4 << endl; //E } else { c1 = - c1; //E c2 = ~c2; //E Complex c4 = c3++; //E cout << ++c4; //E } }

Explanation Notes: E00. Complex Number, in simple words, has two parts (1) Real and (2) Imaginary. You have to treat both the parts separately for the purpose of addition, subtraction etc. For example, 2+3 i is a Complex Number that has 2 as Real and 3 as Imaginary, whereas “ i ” is part of notation to write a Complex Number. In the Explanation Notes, wherever d is referred to as double value and c1 , c2 , c3 etc. are referred to as Complex value E01. Default Constructor: It would simply make both the parts zero. E02. Copy Constructor: It would perform a simple member wise copy. E03. Type Cast Constructor: It would assign the received value to Real part only, Imaginary will remain zero. E04. Parameterized Constructor: It would simply assign first parameter to Real and second to Imaginary part. E05. Assignment Operator E06. Output Operator: It should display the value in standard notation of Complex Number, i.e., 2+3 i. E07. Input Operator: It should prompt for each part of the value, e.g., Real: 2. Imaginary: 3654. E08. Plus Operator: It will not change the two operands rather it should return the result as Complex Number, e.g. c2 + c3 will give a Complex Number that has Real equals sum of Real parts of c2 and c3, similarly Imaginary equals sum of Imaginary parts of c2 and c3. Overload this operator for all the possibilities, like, c2 + c3, c2 + d, and d + c2. E09. Add Operator: It should be able to handle c1+=c2, c1+=d, and d+=c E10. Minus Operator: Same as Plus Operator, Real part of difference of operand1 and operand2 will be the difference of Real parts, and Imaginary part will be the difference of Imaginary part. Overload this operator for all the possibilities, like, c2 - c3, c2 - d, and d - c2. E11. Subtract Operator: It should be able to handle c1-=c2, c1-=d, and d-=c E12. Comparison (Relational/Equality) Operators: Real part of operand1 will be compared with Real part of operand2 and same with Imaginary part of both operands. However, Real part has precedence, e.g., 2+3 i is greater than 1+2543 i. E13. Negative Operator (Unary): It will change the sign of both parts (Real and Imaginary) E14. Complement Operator (Unary): It will swap both the parts with each other. E15. Post-Increment Operator (Unary): It will increment (by 1) the value of Real part only. E16. Pre-Increment Operator (Unary): It will increment (by 1) the value of Real part only. E99. No need to Overload Logical AND, Logical OR, and Conditional Operator. Q. 2 Write an Abstract Data Type (ADT) named CMatrix having following data members:

  1. Rational operator! ( ); Returns Inverse of calling rational object (this object).
  2. ostrream& operator << (ostream& os , Rational& r1 ) Input the rational number.
  3. istrream& operator >> ( IStrream& is , Rational& r1 ) Ouput the rational number.

Question # 15

Constructors, Destructors, Wrapper Functions and Friend Functions

Q.1 Create a class called Student.

  1. Its data members are as follows Rollno from int. Cgpa from float / Name object from class String.
  2. Write appropriate constructors, destructors and wrapper functions.
  3. Use functions from string class for manipulating name. Write main that initializes an array of students and pass in friend function showrank. The showrank will show result in the following form. Rank1 (3.5-4.0) Rank 2(3.0-3.49) Rank 3 (2.0-2.9) ABC XYZ . . . Where ABC and XYZ represent student’s name.

Question # 16

Constructors, Destructors, Inheritance and Polymorphism

Q.1 Write the inheritance hierarchy of Community for university. Use the class Community to further specialization of university people. Derive two classes Employee and Student from class Community. Further derive two classes Faculty and Staff from class Employee. Write a class Administrator acting as Faculty and staff both. The four data members for class community are Name, Address, Age, and Id. The two data members for class student are Id and Salary. The three data members for class student are Id, Degree and CGPA. The only data member for Faculty is Qualification. Similarly the only data member for staff is Rank. Again the only data member for Administrator is Designation. For all classes provide appropriate constructor, destructor and wrapper functions.

Write a main in which a base class pointer will be used to call wrapper functions for every derived class from base class Community (Hint: Base class pointer is of Community.). Q.2 Create a base class Employee having three data members’ first name and last name (use character pointer for this) and earning. Then write derived classes of 1. Employee that are Boss who gets paid a fixed weekly salary regardless of numbers of hours worked.

  1. Employee that are CommissionWorker who gets a flat base salary plus a percentage of sales.
  2. Employee that are Pieceworker who gets paid by the number of items produced.
  3. Employee that are HourlyWorker who gets paid by the hour and receives overtime pay. The two data members are:
  4. Name of the employee. Note: Name of the employee will be in base class.
  5. Earning of the employee (according to type). Provide appropriate constructors and destructors. Also the following functions. An earnings function call certainly applies generically to all employees. But the way each person’s earnings are calculated depends on the class of employee. Getter functions will be used to print the name of the employee and earnings of the employee. Write appropriate constructors and destructors and wrapper functions for all classes. The two functions that will be common in all classes will be calculateearning and printdata. Write a main that declares all types of employee. Declare a base class pointer variable employee. Assign address of any derived class employee in base class pointer variable. Call getter function of derived class using base class pointer variable. Q.3 Create a hierarchy of the classes for observing different types of inheritance. For this create four classes namely Shape, Point, Circle and Cylinder. All of these classes are linked by inheritance. Write a class Shape having a data member ShapeName. Write a function that prints ShapeName.(Hint: In this class shape is not the name of any shape. So there is restriction this function cannot be called.). Write class Point derived from class Shape. Point has two data members as x and y coordinates of a single point. Override the function print in the base class Shape. Write a class Circle derived from point. Circle has radius as data member. The other two data members that are used for centre for any circle are from its base class Point. Override the function print accordingly. Write a class Cylinder derived from Circle. Cylinder has height as data member. The other three data members that are needed for Cylinder are from its base class Circle. Override the function print accordingly. Provide appropriate constructors, destructors and wrapper functions for all classes in hierarchy.

//only function needed to set values is as under: void setnames (char *sname=”un-assigned”, char *fname=””, int id=0) { strcpy (fname,firstname); strcpy (sname,surname); this->id = id; }}; has been defined, and the random access file has been opened properly. Assume all header files are included. Do all the following tasks in main. a) Initialize the file”nameid.txt” with 20 records containing surname=“un-assigned”, firstname =””, and id = 0. b) Input surname, firstname and age of last 5 records out of 20 from user and write them to file. (Order should be maintained only last five records should be updated with new values.) c) Take an id from user which should be grater than 0. d) Update a record with new values that if id entered by user matches with any id already saved.

Revision of All topics Covered

Q.1 Write code to execute the following code: void main () { power (5, 2); power(5.2, 4); power (40,000, 2); } Note: where first argument in this power function is the number that will be raised to value passed in second argument. Q. 2 Write an ADT namely Safearray that is preferable to built-in arrays in c++. Safearray will check the index each time the array is accessed to ensure it is not out of bounds. The size of the safe array will be given at the time of initialization. If not given by user some max value will be used to specify size. Provide the facility user can specify both the upper and lower bound of the array (indexes running from 100 to 200, for example). You will need to add two argument constructor that specifies the upper and lower bounds. Note: You can use mapping.

Q.3 Write down the class String for correct execution of the following main( ) : void main() { String s1('a'), s2("ABC"), s3=s2; String s4="abc", s5='A'; s2 = s5 = s4; cout << s2 << endl; cin >> s4; String s[3] = {“hufc”, “ hiit”, “ hims”}; for (int k =0; k<3; k++) cout << s[k] << endl; s2 = s5 + s4; s3 = s5 + ‘R’; s4 = s3 + ‘W’ + s4; s5 = “DD” + s4; s2 = s5 = ‘Y’; } Q.4 Fill in the blanks in each of the following : a) Members of the class specified as private members are accessible only to member functions of the class and __________________ of the class. b) The set of public member functions of the class is referred to as the class __________________. c) The default access for members of the class is __________________. d) The __________________ operator dynamically allocates memory for an object of a specified type and returns a pointer to that type. e) A __________________ data member represents class-wide information. f) The C++ operators that cannot be overloaded are __________________(any three). g) An object of a class can be treated as an object of its __________________ corresponding__________________ class. h) A “has a” relationship between classes represents __________________ and an” is a” relationship between classes represents __________________. i) The three member access specifies are __________________. j) If a class contains one or more pure virtual function, it is an _________________. k) A function call resolved at run time is referred to as ______________ binding. l) The stream manipulators ___________, ___________, and ___________ specify that integers should be displayed in octal, hexadecimal and decimal formats, respectively. m) The endl manipulator is used for __________________. n) The difference between function template and template function is __________________. o) __________________ are runtime errors. p) A stream is __________________ of bytes.