22
Page 1 of 22 INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind Singh Indraprastha University, Approved by AICTE, New Delhi) A-4, Paschim Vihar, Rohtak Road, New Delhi-110063, Visit us at:http://www.bvicam.in/ Course Code: MCA-154 Course Name: Object Oriented Programming in C++ Introductory Assignment I Q 1. Write the prototype and definition for a function named Perimeter(), which returns an unsigned long int and that takes two parameters, both unsigned short ints. The two parameters represent the length and width of a rectangle. Have the function return the perimeter (twice the length plus twice the width). Q 2. You can convert temperature from degrees Celsius to degrees Fahrenheit by multiplying by 9/5 and adding 32. Write a program that allows the user to enter a floating-point number representing degrees Celsius, and then displays the corresponding degrees Fahrenheit. Q 3. On a certain day the British pound was equivalent to $1.487 U.S., the French franc was $0.172, the German deutschemark was $0.584, and the Japanese yen was $0.00955. Design a program that allows the user to enter an amount in dollars, and then displays this value converted to these four other monetary units. Q 4. Assume that you want to generate a table of multiples of any given number. Write a program that allows the user to enter the number and then generates the table, formatting it into 10 columns and 20 lines. Interaction with the program should look like this (only the first three lines are shown): Enter a number: 8 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 126 144 160 Q 5. Create a structure called employee that contains two members: an employee number (type int) and the employee’s compensation (in dollars; type float). Ask the user to fill in this data for three employees, store it in three variables of type struct employee, and then display the information for each employee. Q 6. Write a function called reversit() that reverses a C-string (an array of char). Use a for loop that swaps the first and last characters, then the second and next-to-last characters, and so on. The string should be passed to reversit() as

INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 1 of 22

INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM)

(Affiliated to Guru Gobind Singh Indraprastha University, Approved by AICTE, New Delhi) A-4, Paschim Vihar, Rohtak Road, New Delhi-110063, Visit us at:http://www.bvicam.in/

Course Code: MCA-154 Course Name: Object Oriented Programming in C++

Introductory Assignment I Q 1. Write the prototype and definition for a function named Perimeter(), which

returns an unsigned long int and that takes two parameters, both unsigned

short ints. The two parameters represent the length and width of a rectangle.

Have the function return the perimeter (twice the length plus twice the

width).

Q 2. You can convert temperature from degrees Celsius to degrees Fahrenheit by

multiplying by 9/5 and adding 32. Write a program that allows the user to

enter a floating-point number representing degrees Celsius, and then

displays the corresponding degrees Fahrenheit.

Q 3. On a certain day the British pound was equivalent to $1.487 U.S., the French

franc was $0.172, the German deutschemark was $0.584, and the Japanese

yen was $0.00955. Design a program that allows the user to enter an amount

in dollars, and then displays this value converted to these four other

monetary units.

Q 4. Assume that you want to generate a table of multiples of any given number.

Write a program that allows the user to enter the number and then generates

the table, formatting it into 10 columns and 20 lines. Interaction with the

program should look like this (only the first three lines are shown): Enter a

number: 8

8 16 24 32 40 48 56 64 72 80

88 96 104 112 120 128 136 126 144 160 Q 5. Create a structure called employee that contains two members: an employee

number (type int) and the employee’s compensation (in dollars; type float). Ask the user to fill in this data for three employees, store it in three variables of type struct employee, and then display the information for each employee.

Q 6. Write a function called reversit() that reverses a C-string (an array of char).

Use a for loop that swaps the first and last characters, then the second and

next-to-last characters, and so on. The string should be passed to reversit() as

Page 2: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 2 of 22

an argument. Write a program to exercise reversit(). The program should get

a string from the user, call reversit(), and print out the result. Use an input

method that allows embedded blanks. Test the program with Napoleon’s

famous phrase, “Able was I ere I saw Elba.”

II Q 7. Create a class called employee that contains a name (an object of class string)

and an employee number (type long). Include a member function called

getdata() to get data from the user for insertion into the object, and another

function called putdata() to display the data. Assume the name has no

embedded blanks. Design a main() program to exercise this class. It should

create an array of type employee, and then invite the user to input data for

up to 100 employees. Finally, it should print out the data for all the

employees.

Q 8. Read 5 numbers and find largest out of them through overloading of new

and delete operators.

const int NUM=5;

class number{int *s; Public: Void input(); Int large(void);}; III Q 9. Create a time class that includes integer member values for hours, minutes,

and seconds. Make a member function get_time() that gets a time value from

the user, and a function put_time() that displays a time in 12:59:59 format.

Add error checking to the get_time() function to minimize user mistakes.

This function should request hours, minutes, and seconds separately, and

check each one for ios error status flags and the correct range. Hours should

be between 0 and 23, and minutes and seconds between 0 and 59. Don’t input

these values as strings and then convert them; read them directly as integers.

This implies that you won’t be able to screen out entries with superfluous

decimal points, as does the ENGL_IO program in this chapter, but we’ll

assume that’s not important. In main(),use a loop to repeatedly get a time

value from the user with get_time() and then display it with put_time(), like

this:

Enter hours: 11 Enter minutes: 59 Enter seconds: 59 time = 11:59:59

Do another (y/n)? y Enter hours: 25 Hours must be between 0 and 23 Enter hours: 1 Enter minutes: 10 Enter seconds: five Incorrect seconds input Enter seconds: 5 time = 1:10:05.

Page 3: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 3 of 22

IV Q10. Create a list for character elements using List Container

Q11. Design a solution to create a set with elements from 1 to 6 inserted in

arbitrary order

Practice Questions (Practical)

I Q 1. Design a function in C++ to merge the contents of two sorted arrays A & B into third array C. Assuming array A is sorted in ascending order, B is sorted in descending order, the resultant array is required to be in ascending order.

Q 2. Design a function in C++ to combine the contents of two equi-sized arrays A and B by computing their corresponding elements with the formula 2*a[I]+3*b[I]; where value I varies from 0 to N-1 and transfer the resultant content in the third same sized array.

Q 3. Design appropriate functions for the following:- a) Binary search b) Insertion sort c) Selection sort d) Bubble sort

Design a menu-driven solution to accept an unsorted array from the user, sort its elements using the user choice of sorting algorithm from (b) to (d) and then search for a number in the same using binary search?

Q 4. Consider the following structure, which implements passengers Queue for a train. Create the definition of function Insert() (whose prototype is shown below); to insert a new node in the queue with required information : struct NODE { long Ticketno; char Pname[20]; NODE *NEXT; }; class queueoftrain { NODE *Rear, *Front; public: queueoftrain() { Rear=Front=NULL; } void Insert(); void Delete(); ~queueoftrain(); }; Simulate the above design with appropriate code.

Q 5. Evaluate the following postfix expression-using stack and show the contents of stack after execution of each operation:

Page 4: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 4 of 22

20, 45, +, 20, 10, -, 15, +, * Q 6. Given the following class :

Char *msg[]={“over flow”,”underflow”}; Class stack { int top, stk[5]; void err_rep(int e_num) { cout<<msg[e_num]; } public: void init() { top=0; void push(int); void pop(); }; Define push outside the stack. In your definition take care of overflow condition. Function push has to invoke err_rep to report overflow.

Q 7. Design a menu-driven program for the following :- Main Menu 1) Create Linked List 2) Inserting a node at End/Start/In between 3) Deleting a node at End/Start/In between 4) Displaying nodes from the List 5) Exit

Q 8. 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. Develop a program that can read values for the class objects and add one object DM with another object DB. Use a friend function to carry the addition operation. The object that stores the results may, by a DM object or DB object, depending on the units in which the results are required. The display should be in the format of feet and inches or meters and centimeters depending on the object on display.

Q 9. Define a class BOOK with the following specifications: Private members of the class BOOK are : BOOK_NO integer type BOOK_TITLE 20 characters BOOK_TYPE 20 characters PRICE float(price per copy) TOTAL_COST() A function to calculate the total cost for N number of copies, where N is passed to the function as an argument. Public members of the class BOOK are : INPUT() Function to read BOOK_NO,BOOK_TITLE,PRICE PURCHASE() Function to ask the user to input the number of copies to be purchased. It invokes TOTAL_COST() and prints the total cost to be paid by the user. Accept the 10 records of the books and display the information of

Page 5: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 5 of 22

those books, whose theme is Comedy. Q 10. Create a class called box whose constructor function is passed three double

values, each of which represents the length of one side of a box. From the box class compute the volume of the box and store the result in a double variable. Include a member function called vol() that displays the volume of each box object and destructor, which removes the space allocated.

Q 11. A bookshop maintains the inventory of books that are being sold at the shop. The list includes details such as author, title, price, publisher and stock position. Whenever a customer wants a book, the sales person inputs the title and author and the system searches the list and displays whether it is available or not. If it is not, an appropriate message is displayed. If it is, then the system displays the book details and requests for the number of copies required. If the requested copies are available, the total cost of the required copies is displayed, otherwise the message “Sorry! These many copies are not in stock” is displayed. Design a program using a class called stock with suitable member functions, copy constructor and destructor.

Q 12. Design a C++ program that uses a function to check whether a given number is divisible by another number or not. However, if the second number is missing, the function checks whether the given number is prime or not. (Use Function Overloading)

Q 13. Imagine a publishing company that markets both books and audio-cassette versions of its works. Create a class publication that stores the title (a string) and price(type float) of a publications. From this class derive two classes: book, which adds a page count (type int) and tape which adds a playing time in minutes(type float). Each of these three classes should have a getdata() function to get its data from the user and putdata() function to display its data. Design a main () program to test the book and tape classes by creating instances of them, asking the user to fill in their data with getdata(), and then displaying the data with putdata().

Q 14. The sizeof operator can be used to determine the number of bytes occupied in memory by a variable of a certain type. For example, sizeof(short) is equivalent to 2. Design a C++ program that displays the memory space required by each fundamental type on screen

Q 15. Create a C++ program that defines a string containing the following character sequence:

“I have learned something new again! “

and displays the length of the string on screen.

Read two lines of text from the keyboard. Concatenate the strings using " * " to separate the two parts of the string. Output the new string on screen.

Q 16. Design a C++ program that reads any given character code (a positive integer) from the keyboard and displays the corresponding character and the character code as a decimal, an octal, and a hexadecimal on screen.

Page 6: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 6 of 22

Q 17. Design a program for the following numerical game:

The computer stores a random number between 1 and 15 and the player (user) attempts to guess it. The player has a total of three attempts. After each wrong guess, the computer tells the user if the number was too high or too low. If the third attempt is also wrong, the number is output on screen.

The player wins if he or she can guess the number within three attempts. The player is allowed to repeat the game as often as he or she wants.

Note Use the system time to seed the random number generator as shown opposite. The time() function returns the number of seconds since 1/1/1970, 0:0. The long value of the sec variable is converted to unsigned by unsigned(sec) and then passed to the srand() function.

Q 18. Design a filter program to display the text contained in any given file. The program should filter any control characters out of the input with the exception of the characters \n (end-of-line) and \t (tabulator), which are to be treated as normal characters for the purpose of this exercise. Control characters are defined by codes 0 to 31.

A sequence of control characters is to be represented by a single space character.

A single character, that is, a character appearing between two control characters, is not to be output!

Note Since the program must not immediately output a single character following a control character, you will need to store the predecessor of this character. You may want to use two counters to count the number of characters and control characters in the current string.

Q 19. a. Write the function sum() with four parameters that calculates the arguments provided and returns their sum.

Parameters: Four variables of type long.

Returns: The sum of type long.

Use the default argument 0 to declare the last two parameter of the function sum(). Test the function sum() by calling it by all three possible methods. Use random integers as arguments.

b. Now restructure your program to store the functions main() and sum() in individual source files, for example, sum_t.cpp and sum.cpp .

Q 20. a. Write an inline function, Max(double x, double y), which returns the maximum value of x and y. (Use Max instead of max to avoid a collision with other definitions of max.) Test the function by reading values from the keyboard.

Page 7: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 7 of 22

Can the function Max() also be called using arguments of the types char, int, or long?

b. Now overload Max() by adding a further inline function Max(char x, char y) for arguments of type char .

Can the function Max() still be called with two arguments of type int? Q 21. The factorial n! of a positive integer n is defined as

n! = 1*2*3 . . . * (n-1) * n

Where 0! = 1

Write a function to calculate the factorial of a number.

Argument: A number n of type unsigned int. Returns: The factorial n! of type long double.

Formulate two versions of the function, where the factorial is

a. calculated using a loop b. calculated recursively

Test both functions by outputting the factorials of the numbers 0 to 20 II Q 22. Design a void type function called circle()to calculate the circumference and

area of a circle. The radius and two variables are passed to the function, which therefore has three parameters:

Parameters: A read-only reference to double for the radius and two references to double that the function uses to store the area and circumference of the circle.

Note Given a circle with radius r:

Area = p * r * r and circumference = 2 * p * r where p = 3.1415926536

Test the function circle() by outputting a table containing the radius, the circumference, and the area for the radii 0.5, 1.0, 1.5, . . . , 10.0.

Q 23. Create a function quadEquation() that calculates the solutions to quadratic equations. The formula for calculating quadratic equations is shown opposite.

Page 8: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 8 of 22

Arguments: The coefficients a, b, c and two pointers to both solutions. Returns: false, if no real solution is available, otherwise true.

Test the function by outputting the quadratic equations Q 24. A program needs a class to represent the date.

• Define the class Date for this purpose using three integral data members for day, month, and year. Additionally, declare the following methods:

• void init( int month, int day, int year); • void init(void);

void print(void);

Store the definition of the class Date in a header file.

• Implement the methods for the class Date in a separate source file: 1. The method print() outputs the date to standard output using

the format Month-Day-Year. 2. The method init() uses three parameters and copies the values

passed to it to corresponding members. A range check is not required at this stage, but will be added later.

3. The method init() without parameters writes the current date to the corresponding members.

Note Use the functions declared in ctime

time_t time(time_t *ptrSec) struct tm *localtime(const time_t *ptrSec);

4. The structure tm and sample calls to this function are included opposite. The type time_t is defined as long in ctime.

5. The function time() returns the system time expressed as a number of seconds and writes this value to the variable referenced by ptrSec. This value can be passed to the function localtime() that converts the number of seconds to the local type tm date and returns a pointer to this structure.

• Test the class Date using an application program that once more is stored in a separate source file. To this end, define two objects for the class and display the current date. Use object assignments and—as an additional exercise—references and pointers to objects.

Q 25. A warehouse management program needs a class to represent the articles in stock.

• Define a class called Article for this purpose using the data members and methods shown opposite. Store the class definition for Article in a separate header file. Declare the constructor with default arguments for each parameter to ensure that a default constructor exists for the

Page 9: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 9 of 22

class. Access methods for the data members are to be defined as inline. Negative prices must not exist. If a negative price is passed as an argument, the price must be stored as 0.0.

• Implement the constructor, the destructor, and the method print() in a separate source file. Also define a global variable for the number of Article type objects.

The constructor must use the arguments passed to it to initialize the data members, additionally increment the global counter, and issue the message shown opposite.

The destructor also issues a message and decrements the global counter.

The method print() displays a formatted object on screen. After outputting an article, the program waits for the return key to be pressed.

• The application program (again use a separate source file) tests the Article class. Define four objects belonging to the Article class type:

1. A global object and a local object in the main function. 2. Two local objects in a function test() that is called twice by

main(). One object needs a static definition. The function test() displays these objects and outputs a message when it is terminated.

Use articles of your own choice to initialize the objects. Additionally, call the access methods to modify individual data members and display the objects on screen.

• Test your program. Note the order in which constructors and destructors are called.

Q 26. Date class containing members for day, month, and year was defined. Now extend this class to add additional functionality. The methods are shown on the opposite page.

• The constructors and the method setDate() replace the init method used in the former version. The default constructor uses default values to initialize the objects in question. The setDate() method without any parameters writes the current date to the object.

• The constructor and the setDate() method with three parameters do not need to perform range checking. This functionality will be added in the next exercise.

• The methods isEqual() and isLess() enable comparisons with a date passed to them.

• The method asString() returns a reference to a string containing the date in the format mm-dd-year, e.g. 03-19-2006. You will therefore

Page 10: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 10 of 22

need to convert any numerical values into their corresponding decimal strings. This operation is performed automatically when you use the << operator to output a number to the standard output cout. In addition to the cin and cout streams, with which you are already familiar, so-called string streams with the same functionality also exist. However, a string stream does not read keyboard input or output data on screen. Instead, the target, or source, is a buffer in main memory. This allows you to perform formatting and conversion in main memory.

• Use an application program that calls all the methods defined in the class to test the Date class.

The Date class does not ensure that an object represents a valid date. To avoid this issue, add range checking functionality to the class. Range checking is performed by the constructor and the setDate() method with three parameters.

• First, write a function called isLeapYear() that belongs to the bool type and checks whether the year passed to it is a leap year. Define the function as a global inline function and store it in the header file Date.h.

• Modify the setDate() method to allow range checking for the date passed to it. The constructor can call setDate().

• Test the new version of the Date class. To do so, and to test setDate(...), read a date from the keyboard.

Q 27. A sports club needs a program to manage its members. Your task is to define and test a class called Member for this purpose.

• Define the Member class using the data members shown opposite. Use the Date class defined in the last chapter for your definition. Since a member's birthday will not change, the data member for birthdays must be defined as a const.

Overload the constructor to allow for entering a date as an object as well as three values for day, month, and year.

• Implement the necessary methods. • Test the new Member class by creating at least two objects with the

data of your choice and calling the methods you defined. • Add a static member called ptrBoss to the class. This pointer indicates

the member who has been appointed as chairperson. If no chairperson has been appointed, the pointer should point to NULL.

• Additionally, define the static access methods getBoss() and setBoss(). Use a pointer to set and return the object in question.

• Test the enhanced Member class by reading the number of an existing member, making the member the new chairperson and displaying the

Page 11: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 11 of 22

chairperson using getBoss().

Q 28. Create a program to simulate the signal positions for two sets of traffic lights at a junction. Use the class Lights as defined in this chapter for your program.

• Each set of lights is switched through the phases red, amber, green, amber, red, and so on. You must ensure that one set of lights can be only in the amber or green state when the other set of lights is red.

• The lights operate in an infinite loop that can be terminated by interrupting the program. You can use the key combination <Ctrl>+<C> for DOS and Windows and the Interrupt key, i.e., normally the <Del> key, for UNIX.

• The status of the lights is constant for a certain number of seconds. For example, the green phase can take 20 seconds and the amber phase 1 second. These values can be different for each set of lights. Define an auxiliary function

inline void wait( int sec)

The function returns after the stipulated number of seconds. To do so, you can call the standard function time() in a loop

Q 29. Design a C++ program that reads a maximum of 100 integers from the keyboard, stores them in a long array, sorts the integers in ascending order, and displays sorted output. Input can be terminated by any invalid input, such as a letter.

Note Use the bubble sort algorithm to sort the array. This algorithm repeatedly accesses the array, comparing neighboring array elements and swapping them if needed. The sorting algorithm terminates when there are no more elements that need to be swapped. You use a flag to indicate that no elements have been swapped.

II Q 30. Design a program that outputs all prime numbers less than 1000. The program should also count the number of prime numbers less than 1000. An integer >= 2 is a prime number if it is not divisible by any number except 1 and itself. Use the Sieve of Eratosthenes:

To find primary numbers simply eliminate multiples of any primary numbers you have already found, i.e.:

first eliminate any multiples of 2 ( 4, 6, 8, ... ),

then eliminate any multiples of 3 ( 6, 9, 12, ...),

then eliminate any multiples of 5 ( 10, 15, 20, ..) // 4 has already been eliminated

and so on. Q 31. Design a C++ program to create the screen output shown opposite. The

Page 12: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 12 of 22

following banner

* * * B R E A K * * *

is to be displayed in the center of the window and scrolled left. You can scroll the banner by beginning string output with the first character, then the second, and so on. Handle the string like a loop where the first letter follows the last letter and output continues until the starting position is reached.

You can use a wait loop to modify the speed of the banner after each string is output.

Q 32. Methods to be implemented for the TelList class

bool append( const string& name, const string& telNr); bool erase( const string& name); int search( const string& name); void print(); int print( const string& name); int getNewEntries();

Menu of the application program

***** Telephone List ***** D = Display all entries F = Find a telephone number A = Append an entry E = Erase an entry Q = Quit the program Your choice: Implement the TellList class as described.

Q 33. Design a program that uses the cin method get() to read a line character by character and stores it in a char array. The line is then output in reverse order. Use a pointer, not an index, to address the array elements

Q 34. The standard function strcmp() performs a lexicographical comparison of two C strings. The opposite page contains an index version of strcmp(). The return value is the difference between two character codes.

Design a pointer version of the function strcmp(). Call this function str_cmp() to distinguish it from the standard function.

Page 13: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 13 of 22

To test the function, use a loop to read two lines of text and output the results of the comparison. The loop should terminate when both strings are empty.

Q 35. a. Design a program that outputs its own name and all command line arguments, each in a separate line.

b. Now extend the program to output its own environment. The environment is a memory area containing strings in the format

NAME=String

A third parameter for the function main() allows access to the environment. This parameter is an array of pointers just like argv. The array elements are char pointers to the environment strings, the last element being a NULL pointer

Q 36. The following frequency was observed during an examination of the relationship between age and blood pressure for 300 males.

Develop a function that calculates the sums of the rows and columns in an int matrix with three rows and five columns. Store the sums of the rows and columns separately in a one-dimensional row or column array.

Arguments: The matrix, the row array, and the column array. Return value: The sum of all the matrix elements.

To test the function, output the matrix, as shown in the graphic opposite along with the computed sums in your main function.

Q 37. You are to develop a class that represents fractions and performs typical arithmetic operations with them.

• Use a header file called fraction.h to define the Fraction class with a numerator and a denominator of type long. The constructor has two parameters of type long: the first parameter (numerator) contains the default value 0, and the second parameter (denominator) contains the value 1. Declare operator functions as methods for - (unary), ++ and -- (prefix only), +=, -=, *=, and /=. The operator functions of the binary operators +, -, *, / and the input / output operators <<, >> are to be declared as friend functions of the Fraction class.

• Implement the constructor for the Fraction class to obtain a positive value for the denominator at all times. If the denominator assumes a value of 0, issue an error message and terminate the program. Then write the operator functions. The formulae for arithmetic operations are shown opposite.

• Then compose a main function that calls all the operators in the Fraction class as a test application. Output both the operands and the results.

Q 38. The < and ++ operators for the sample class DayTime were overloaded at the beginning of this chapter. Now modify the class as follows:

Page 14: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 14 of 22

• Overload the relational operators

< > <= >= == and !=

and the shift operators

>> and << for input and output

using global operator functions. You can define these inline in the header file.

• Then overload both the prefix and postfix versions of the ++ and -- operators. The operator functions are methods of the class. The -- operator decrements the time by one second. The time is not decremented after reaching 0:0:0.

• Write a main function that executes all the overloaded operators and displays their results.

Q 39. Enhance the numerical class Fraction, which you know from the last chapter, to convert both double values to fractions and fractions to double. In addition, fractions should be rounded after arithmetic operations.

• First declare the simplify() method for the Fraction class and insert the definition on the opposite page in your source code. The method computes the largest common divisor of numerator and denominator. The numerator and the denominator are then divided by this value.

• Add an appropriate call to the simplify() function to all operator functions (except ++ and --).

• Then add a conversion constructor with a double type parameter to the class.

Example:

Fraction b(0.5); // yields the fraction 1/2

Double values should be converted to fractions with an accuracy of three decimal places. The following technique should suffice for numbers below one million. Multiply the double value by 1000 and add 0.5 for rounding. Assign the result to the numerator. Set the value of the denominator to 1000. Then proceed to simplify the fraction.

• You now have a conversion constructor for long and double types. To allow for conversion of int values to fractions, you must write your own conversion constructor for int!

• Now modify the class to allow conversion of a fraction to a double type number. Define the appropriate conversion function inline.

Use the function main() to test various type conversions. More specifically, use assignments and arithmetic functions to do so. Also compute the sum of

Page 15: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 15 of 22

a fraction and a floating-point number.

Output the operands and the results on screen Q 40. Design a global function called splice() that "splices" two int arrays together

by first allocating memory for a dynamic array with enough room for both int arrays, and then copying the elements from both arrays to the new array, as follows:

• first, the elements of the first array are inserted up to a given position, • then the second array is inserted, • then the remainder of the first array is appended.

Arguments: The two int arrays, their

Q 41. Design a global function called merge() that merges two sorted int arrays by first allocating memory for a dynamic array with enough room for both int arrays and then inserting the elements of both arrays into the new array in sequence.

Arguments: The two int arrays and their length. Return value: A pointer to the new array

To test the function, modify the program used to sort arrays. III Q 42. Complete and test the implementation of a linked list.

• First define the access methods shown opposite. Then overload the << operator for the class ListEl to allow formatted output of the data in the list elements. You can use the asString() in the date class to do so.

• Then implement the destructor for the List class. The destructor will release the memory used by all the remaining elements. Make sure that you read the pointer to the successor of each element before destroying it!

• Implement the methods pushBack() and popFront() used for appending and deleting list elements.

• Overload the operator << in the List class to output all the data stored in the list.

• Test the List class by inserting and deleting several list elements and repeatedly outputting the list.

Q 43. Derive two classes, DepAcc and SavAcc, from the Account class." Additionally define an overdraft limit and an interest rate for the DepAcc class. The SavAcc contains the members of the base class and an interest rate.

• For both classes, define constructors to provide default values for all parameters, add access methods, and add a display() method for screen output.

• Test the new classes by initializing objects of the DepAcc and SavAcc types in the object declarations and outputting them. Then modify

Page 16: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 16 of 22

both a savings and a deposit account interactively and display the new values.

Q 44. A supermarket chain has asked you to develop an automatic checkout system. All products are identifiable by means of a barcode and the product name. Groceries are either sold in packages or by weight. Packed goods have fixed prices. The price of groceries sold by weight is calculated by multiplying the weight by the current price per kilo.

Develop the classes needed to represent the products first and organize them hierarchically. The Product class, which contains generic information on all products (barcode, name, etc.), can be used as a base class.

• The Product class contains two data members of type long used for storing barcodes and the product name. Define a constructor with parameters for both data members. Add default values for the para-meters to provide a default constructor for the class. In addition to the access methods setCode() and getCode(), also define the methods scanner() and printer(). For test purposes, these methods will simply output product data on screen or read the data of a product from the keyboard.

• The next step involves developing special cases of the Product class. Define two classes derived from Product, PrepackedFood and FreshFood. In addition to the product data, the PrepackedFood class should contain the unit price and the FreshFood class should contain a weight and a price per kilo as data members.

In both classes define a constructor with parameters providing default-values for all data members. Use both the base and member initializer.

Define the access methods needed for the new data members. Also redefine the methods scanner() and printer() to take the new data members into consideration.

• Test the various classes in a main function that creates two objects each of the types Product, PrepackedFood and FreshFood. One object of each type is fully initialized in the object definition. Use the default constructor to create the other object. Test the get and set methods and the scanner() method and display the products on screen.

Q 45. An automatic checkout system for a supermarket chain needs to be completed.

• Declare the virtual methods scanner() and printer() in the base class Product. Also define a virtual destructor.

• Write the record() function, which registers and lists products

Page 17: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 17 of 22

purchased in the store in a program loop.

The function creates an array of 100 pointers to the base class, Product. The checkout assistant is prompted to state whether a prepacked or fresh food item is to be scanned next. Memory for each product scanned is allocated dynamically and referenced by the next pointer in the array. After scanning all the available items, a sequential list is displayed. The prices of all the items are added and the total is output at the end.

• Now create an application program to simulate a supermarket checkout. The checkout assistant is prompted in a loop to state whether to define a new customer. If so, the record() function is called; if not, the program terminates.

Q 46. class InhomList { private: Cell* first; protected: Cell* getPrev(const string& s); Cell* getPos(const string& s); void insertAfter(const string& s, Cell* prev); void insertAfter(const string& s,const string& b, Cell* prev); void erasePos(Cell* pos); public: InhomList(){ first = NULL; } InhomList(const InhomList& src); ~InhomList(); InhomList& operator=( const InhomList& src); void insert(const string& n); void insert(const string& n, const string& b); void erase(const string& n); void displayAll() const; };

Modify and complete the definition of the class InhomList, which represents an inhomogeneous list.

• Write the destructor for the InhomList class. The destructor releases the memory occupied by the remaining list elements.

• Implement the getPrev() method and both versions of the insert() and insertAfter() methods. The algorithm needed for inserting list elements was described in the section "Implementing an Inhomogeneous List."

Page 18: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 18 of 22

• Implement the displayAll() method, which walks through the list sequentially, outputting each element.

• Test insertion and output of list elements. Check whether the comments on the objects are output, if present.

• Define the getPos() method, which locates the position of an element to be deleted. If the element is in the list, its address is returned. Otherwise a NULL pointer is returned.

• Write the erasePos() method, which deletes a list element at a given position. Pay attention to whether the element to be deleted is the first or any other element in the list. Since the destructor for Cell was declared virtual, only one version of the deletePos() method is necessary.

• Define the erase() method, which deletes a list element with a given name from the list.

• Test deletion of list elements. Continually display the remaining elements in the list to be certain.

• Now implement the copy constructor and assignment. Use the insert() to construct the list, calling the applicable version of the method. You can call the typeid() operator to ascertain the type of the list element currently to be inserted. The operator is declared in the header file typeinfo.

Example:

if( typeid(*ptr) == typeid(DerivedEl)) ...

The expression is true if ptr references a DerivedEl type object.

• Then test the copy constructor and the assignment

Q 47. Implement exception handling for the Fraction class, which is used to represent fractions (see Exercise 2, Chapter 19). Dividing by 0 throws an exception that affects the constructor for the Fraction class and the operator functions / and >>.

• Define the exception class DivError, which has no data members, within the Fraction class. The exception class is of the following type

Fraction::DivError

Add an appropriate exception specification to the declarations of the constructor and the operator functions / and >>.

• Change the definition of the constructor in the Fraction class. If the value of the denominator is 0, a DivisionByZero type exception should be thrown.

• Similarly modify the operator functions. • Now write a main function to test the various exceptions. You will

Page 19: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 19 of 22

need to arrange three different try and catch blocks sequentially.

The first try/catch block tests the constructor. Create several fractions, including some with a numerator value of 0 and one with 0 as its denominator. The exception handler should issue the error message shown opposite.

The second try/catch block tests divisions. Use a statement to attempt to divide by 0. The corresponding exception handler should send the second error message shown opposite to your standard output.

The third try/catch block reads numerators and denominators of fractions in dialog. If the value of the denominator is 0, the denominator is read again. If the value is still 0, the third error message as shown opposite is output and the program terminates.

Q 48. class IndexFile { private: fstream index; string name; // Filename of the index public: IndexFile(const string s) throw(OpenError); ~IndexFile( ){ index.close(); } void insert( long key, long pos) throw(ReadError, WriteError); long search( long key) throw(ReadError); void retrieve(IndexEntry& entry, long pos ) throw( ReadError); };

Class AccFile

enum TypeId { ACCOUNT, DEPOSIT, SAVINGS }; class AccFile { private: fstream f; string name; // Filename of primary file public: AccFile(const string s) throw(OpenError); ~AccFile(){ f.close(); } long append( Account& acc) throw(WriteError); Account* retrieve( long pos ) throw(ReadError); };

Complete and test the implementation of the IndexFileSystem class. The methods should throw exceptions of an appropriate FileError type if an error

Page 20: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 20 of 22

occurs.

a. Complete the constructor of the IndexFile class in order to throw an exception of the type OpenError if the file can not be opened.

b. Write the retrieve() method for the IndexFile class. The method retrieves a record at a given position in the index.

c. Define the search() method, which looks up an index entry for an account number passed to it as an argument. Base the method on the binary search algorithm.

Return value: The position of the record found, or -1 if the account number is not found in the index.

d. Then define the retrieve() method for the AccFile class, which first evaluates the type field at a given position in the account file, then dynamically allocates memory for an object of the appropriate type, and finally reads the data for an account from the file.

e. Develop a main() function that uses a try block to create an IndexFileSystem type object and to insert several accounts of various types into the index file. The subsequent user dialog reads a key and displays the corresponding record on screen. Write an exception handler to handle the various errors that could occur. The name of the file and the cause of the error must be output in any case of error.

Q 49. Your task is to encrypt data to prevent spying during data communications. The sender uses a filter to encrypt the data in question, and the receiver uses the same filter to decrypt the transmission.

a. Define the function swapBits() that swaps two bits in an int value. The int value and the positions of the bits to be swapped are passed as arguments to the function. The return value is the new int value. If one of the positions passed to the function is invalid, the int value should be returned unchanged.

b. Write a filter that swaps the bits at bit positions 5 and 6, 0 and 4, and 1 and 3 in all characters except control characters (defined as ASCII Code >= 32).

Test the filter by writing the encrypted output to a file and then using the same filter to output the new file. The output must comprise the original unencrypted data.

IV Q 50. Define a class template Array<T, n> to represent an array with a maximum of n elements of type T. Attempting to address an array element with an invalid index should lead to an exception of the BadIndex (defined previously) error class being thrown. If there is no space left to insert an element in the array, an exception of the OutOfRange type should be thrown.

• First define the error class OutOfRange without any data members. Use the error class BadIndex

Page 21: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 21 of 22

• Change the existing FloatArr class into a class template, Array<T, n>. Use 255 as the default value for the parameter n of the class template.

This allocates memory for the array statically. Now define a default constructor and a constructor that initializes a given number of array elements with a given value. You do not need to define a copy constructor, a destructor, or an assignment operator.

As access methods define the size() and the length() methods, the size() method returns the maximum number of array elements, that is, n; the length() method returns the current number of elements in the array.

Also define methods for inserting and deleting elements like those defined for the FloatArr class. The methods have a void return type and can throw exceptions of type BadIndex and/or OutOfRange.

Additionally overload the index and shift operators <<. The subscript operator throws BadIndex type exceptions.

• Test the class template Array<T,n> for double and int types first. Define arrays of the appropriate types, then insert and delete elements in the arrays. Output all the elements of the array.

• Modify the test program by adding an array for objects of a class type. Use the DayTime class from Exercise 1, Chapter 19 for this purpose.

Test the array template by defining an array with 5 DayTime class objects and inserting a few objects. Then display all the objects on screen.

IV Q 51. In data communications between two remote computers messages are transmitted via multiple subnets. En route to the target computers, so-called routers store these messages in queues before transmitting them towards the target via the next available line. The routers assume responsibility for route discovery, generally referring to complex address tables.

There are various routing techniques, including a simple algorithm that can do without address tables, the so-called Hot Potato Algorithm. The router simply tries to dispose of incoming messages as quickly as possible by sending each incoming message to the outgoing line with the shortest queue.

• Define a container class VecQueue<T>, which is parameterized with a message type T to represent this scenario. The class comprises an array of queues of type vector< queue<T> > and a data member used to store the current number of queues in the array.

The constructor creates the number of empty queues passed to it as an

Page 22: INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT (BVICAM) (Affiliated to Guru Gobind ...bvicam.in/sites/default/files/subject/preRequisite... · 2019-12-17 · (Affiliated to Guru

Page 22 of 22

argument for the array. Additionally, you will need to declare the methods size(), empty(), push() and pop().

Overload the size() method in two versions: If no argument has been passed to the method, it returns the current number of messages in all queues. If an argument i of type int has been passed, the method returns the current number of messages in the i-th queue. Additionally, overload the empty() and empty(int i) methods, which return true, if all queues or the i-th queue are empty.

The push() method uses the hot potato algorithm to append a message passed to it at the end of the shortest queue.

The pop() and pop(int i) methods are used to simulate the assignment of messages to lines, that is retrieval and removal of messages from queues, in this exercise. The method pop() retrieves the message at the top of a randomly selected queue and deletes it, returning the message. The method pop(int i) retrieves the message at the top of the i-th queue and deletes it, returning the message.

• To test your class, declare a container of the type VecQueue<int> in your main function. A message is represented by a number. Use a loop to insert random numbers between 0 and 99 into the container and relay some of them to the outside lines. Then display the remaining messages on screen, as shown opposite, by calling the pop(int i) method.