December
1998 QUESTION 4 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS
|
| (a) | You are to design a C++ program for
creating and manipulating entries in a telephone book. Consider the following class
definition for a Person entry in a telephone book. class
Person { Person() {number = 0; name = 0;} //
Constructor void display() { // Display a
person
|
|
| (a) | The telephone book is an array of
10,000 Person entries and also an integer that records the number of entries in the
telephone book. Give the definition of a class Telephone_book that contains: (1) the private data items listed above and (2) a default constructor that initialises the number of entries to 0. |
[3] |
| class Telephone_book { | ||
| private: | ||
| Person book[10000]; | [1] | |
| int n; | [1] | |
| public: | ||
|
Telephone_book() { n = 0; } };
|
[1] | |
| (b) | Give the implementation of a methof display that displays the details of every person in the telephone book. | [3] |
| void display() { | ||
| for (int i = 0; i < n; i++) | [2] | |
| book[i].display(); | [1] | |
| }; (1 mark) for using a loop and (1 mark) for correct loop guard; (1 mark) for correctly displaying each entry.
|
||
| (c) | Give the implementation of a method add_person that reads a last name and a telephone number from the user, creates a new person, and adds the person to the end of the array if there is a space. | [8] |
| void add_person() { | ||
| char *name = new char[50]; | [1] | |
| int m; | [1] | |
| cout << "Enter name: "; | ||
| cin >> name; | [1] | |
| cout << "Enter number: "; | ||
| cin >> m; | [1] | |
| if (entries < 10000) { | [1] | |
| Person e = Person(name, n); | [1] | |
| book[entries++] = e; | [2] | |
| } }; (1 mark) for each correct local variable declaration; (1 mark) for each correct input statement; (1 mark) for testing that there is space; (1 mark) for constructing the new Person; (1 mark) for assigning to book; (1 mark) for updating the number of entries.
|
||
| (d) | Give the implementation of a method find that takes a telephone number and displays the person with the corresponding telephone number. If the telephone number does not exist in the telephone book, give an appropriate error message | [6] |
| void find(int m) { | ||
| for (int i=0; i < entries; i++) | [2] | |
| if (book[i].number == m) { | [1] | |
| book[i].display(); | [1] | |
| return; | [1] | |
| } | ||
| } | ||
| cout << "Error: no such number" << endl; | [1] | |
| }; (2 marks) for correct use of a loop with increment and test; (1 mark) for checking numbers against m; (1 mark) for displaying the entry of the book; (1 mark) for terminating loop; (1 mark) for appropriate error message. |