Sie sind auf Seite 1von 78

COS112V/101/3/2009

SCHOOL OF COMPUTING

COS112V

Introduction to Programming 2

IMPORTANT INFORMATION: READ NOW


This is a semester module.

Plan to spend at least 8 hours per week on this module.

To be considered for examination admission in COS112V, a student must meet the following
requirement:
Submit assignment 1 BEFORE 27 February 2009 (first semester registration)
OR
Submit assignment 1 BEFORE 21 August 2009 (second semester registration)

Tutorial Letter 101:


First Tutorial Letter

This tutorial letter (COS112V/101/3/2009) as well as tutorial letter COSALL-F/301/4/2009 contains important
information that you are going to need during the year. Please read them carefully.
2

Another publication which can be of real help is the brochure Unisa: services and procedures. It contains
information about microcomputer laboratories, the library, myUnisa, assistance with study skills, et cetera.

Contents
1 Introduction ................................................................................................................................................................... 4

2 Purpose and outcomes of this module .......................................................................................................................... 4

3 Tutorial Matter .............................................................................................................................................................. 5

3.1 Tutorial matter supplied by Unisa ......................................................................................................................... 5


3.2 Prescribed book ..................................................................................................................................................... 5
3.3 Prescribed software ............................................................................................................................................... 6

4 Additional Reading ........................................................................................................................................................ 6

5 Student Support ............................................................................................................................................................. 7

5.1 Communication with the University ..................................................................................................................... 7


5.2 Contacting the lecturers......................................................................................................................................... 7
5.3 The COS112-V home page ................................................................................................................................... 7
5.4 myUnisa ................................................................................................................................................................. 8
5.5 Student support systems ......................................................................................................................................... 8
5.6 Study groups .......................................................................................................................................................... 8

6 Study Programme .......................................................................................................................................................... 9

6.1 Syllabus ................................................................................................................................................................. 9


6.2 Practical work ....................................................................................................................................................... 9
6.3 Planning your academic year .............................................................................................................................. 10
6.4 Hints on studying this module ............................................................................................................................. 11

7 Examination ................................................................................................................................................................. 12

7.1 Examination Admission ....................................................................................................................................... 12


7.2 Examination period .............................................................................................................................................. 12
7.3 Year mark............................................................................................................................................................. 12

8 The Assignments .......................................................................................................................................................... 13

Assignment 1 (First Semester).............................................................................................................................................. 15

Assignment 2 (First semester) .............................................................................................................................................. 17

Assignment 3 (First Semester and Second Semester) ......................................................................................................... 21


3 COS112V/101/3/2009

Assignment 1 (Second Semester).......................................................................................................................................... 28

Assignment 2 (Second Semester).......................................................................................................................................... 31

Assignment 3 (Second semester ) ......................................................................................................................................... 34

Appendix A: Installing the Software for COS112V ........................................................................................................... 35

1. Software for COS112V .................................................................................................................................................. 35


2. Installing the software .................................................................................................................................................... 36
Method 1 ............................................................................................................................................................................ 36
Method 2 ............................................................................................................................................................................ 36
Uninstalling ........................................................................................................................................................................ 37
3. Using the software .......................................................................................................................................................... 37
Step 1. Starting Dev-C++ .............................................................................................................................................. 37
Step 2. Setting the options ............................................................................................................................................. 37
Step 3. Creating a project............................................................................................................................................... 38
Step 4. Editing a C++ source file ................................................................................................................................... 38
Step 5. Compiling the program ...................................................................................................................................... 39
Step 6. Running the program ......................................................................................................................................... 40
Troubleshooting ............................................................................................................................................................. 40
4. Separate Compilation: Creating Dev-C++ Projects with Multiple Files......................................................................... 41
5. Using the debugger in Dev-C++..................................................................................................................................... 45
What is a debugger? ...................................................................................................................................................... 45
How to use the debugger with a program ...................................................................................................................... 45
The windows that display debug-related information .................................................................................................... 45
How to use the debugger ............................................................................................................................................... 45
6. Printing ........................................................................................................................................................................... 48
Method 1........................................................................................................................................................................ 48
Method 2........................................................................................................................................................................ 48
7. Frequently Asked Questions........................................................................................................................................... 48
8. CodeMate ....................................................................................................................................................................... 50

Appendix B: How to install the software on Vista: ............................................................................................................ 51

Appendix C: Source listings of the sample programs in the textbook .............................................................................. 54

Appendix D: Solution to assignment 3................................................................................................................................. 55


4

1 Introduction
Welcome to COS112V. We hope that you will find this module interesting and stimulating and that you will increase
your knowledge about and your skills in programming in C++. We shall do our best to make your study of this
module successful. You will be well on your way to success if you start studying early in the semester and resolve to
do the assignments properly.

You will receive a number of tutorial letters during the year. A tutorial letter is our way of communicating with you
about teaching, learning and assessment.

Tutorial Letter 101 contains important information about the scheme of work, resources and assignments for this
module. We urge you to read it carefully and to keep it at hand when working through the study material, preparing
the assignments, preparing for the examination and addressing questions to your lecturers.

Please read Tutorial Letter 301 in combination with Tutorial Letter 101 as it gives you an idea of generally important
information when studying at a distance university and within a particular College.

In Tutorial Letter 101, you will find the assignments and assessment criteria as well as instructions on the preparation
and submission of the assignments. This tutorial letter also provides all the information you need with regard to the
prescribed study material and other resources and how to obtain it. Please study this information carefully and make
sure that you obtain the prescribed material as soon as possible.

We have also included certain general and administrative information about this module. Please study this section of
the tutorial letter carefully.

Right from the start we would like to point out that you must read all the tutorial letters you receive during the
semester immediately and carefully, as they always contain important and, sometimes, urgent information.

We hope that you will enjoy this module and wish you all the best!

2 Purpose and outcomes of this module


COS112V is one of a number of first-year Computer Science modules offered by the School of Computing at Unisa.
COS112V focuses on providing an introduction to objects and the object-oriented programming environment using
C++ as programming language. The following topics are covered: file I/O streams as an introduction to objects and
classes; using pre-defined classes such as string and vector; C strings, pointers and dynamic arrays; ADTs
(i.e. user-defined classes including the functions and operators for these classes as well as separate compilation);
recursion; single inheritance and function and class templates.

The specific outcomes for each chapter in the prescribed book for COS112V are given in more detail in the study
guide, Tutorial Letter 501.

The paragraphs below show where COS112V fits into the programming modules offered by the School of
Computing:

• COS111U deals with the basic concepts of programming, using the programming language C++. It is aimed at
students who have not done any programming before.
• COS112V introduces the learner to objects and the object-oriented programming environment. It assumes that
you have completed COS111U or have an equivalent programming qualification. We refer you to Part 2, Section
C of the Unisa Calendar.
5 COS112V/101/3/2009

• COS113W provides a general background to computer systems.


• INF1511 is an introductory course in Delphi programming.
• COS101S introduces the mathematics relevant to Computer Science.

COS112V is also a prerequisite for several second-year modules, namely:

• COS211X focuses on the implementation and use of abstract data types and data structures in an object-oriented
language.
• COS2144 elaborates on the concepts of object-orientation, and the implementation thereof.
• COS2213 introduces students to computer organisation, i.e. the underlying structure of a modern computer.
• COS2338 covers the use of numerical methods in solving scientific and mathematical problems.

3 Tutorial Matter
3.1 Tutorial matter supplied by Unisa
The tutorial matter for this module consists of the following:
• this tutorial letter;
• tutorial letter COSALLF/301/4/2009;
• the study guide, tutorial letter COS112V/501/3/2009;
• a CD containing the prescribed C++ software;
• additional tutorial letters, containing additional information or solutions to assignments.

When you register, you will receive an inventory letter containing information about your tutorial matter. See also
the booklet entitled Unisa: services and procedures (which you received with your tutorial matter). Check the study
material that you have received against the inventory letter. You should have received all the items listed in the
inventory, unless there is a statement like “out of stock” or “not available”. If any item is missing, follow the
instructions on the back of the inventory letter without delay.

PLEASE NOTE: Your lecturers cannot help you with missing study material. Please contact the Unisa
Contact Centre at 0861 670 411 (RSA only), or +27 11 670 9000 (international calls).

Not all of the above-mentioned tutorial matter will necessarily be available at the time of registration. Tutorial matter
will be despatched to students as soon as it is ready. By following the appropriate links and instructions, tutorial
letters can also be downloaded from the Internet at my.unisa.ac.za or from the School of Computing’s own website
http://osprey.unisa.ac.za.

All information that is made available electronically in the form of tutorial letters will also be sent to you on paper
(except in a very few rare cases). Note that the determining information comes from the paper documents that you
receive. If there is any conflict re for example, dates, prices, times, due dates, assignment numbers, et cetera, refer to
the information published on paper, unless otherwise instructed.

3.2 Prescribed book


The prescribed book for this module is:
6

Walter Savitch. Problem Solving with C++, 7th edition. Pearson International Edition: Addison-Wesley, 2009,
ISBN 9780321549402.

You may also use the 6th edition of the prescribed book.

You are expected to purchase your own copy of the prescribed book. For contact details of official booksellers,
please consult the list of official booksellers and their addresses in Unisa: services and procedures. If you have any
difficulties in obtaining books from these bookshops, please contact the Unisa Contact Centre at 0861 670 411 (RSA
only), or +27 11 670 9000 (international calls).

We will refer to the prescribed book as Savitch.

3.3 Prescribed software


The prescribed software for this module is the MinGW C++ compiler and the DevC++ Integrated Development
Environment (IDE), which are both included in your study package. The prescribed C++ compiler and the IDE are
provided on the CD-ROM that you should have received when you registered. The CD-ROM contains instructions
on how to install the prescribed C++ compiler and the IDE, and how to use the IDE to write, compile and execute
your programs.

These instructions can be accessed from the file index.html on the CD-ROM. There are a number of ways to
view this file. After inserting the CD-ROM into the CD-ROM drive of your computer, do one of the following:
• Click on Run... on the Start menu. In the dialog box that appears, type d:index.html and click on the OK
button.
• Double-click on the My Computer icon on your desktop. In the window that appears, double-click on the CD-
ROM icon (D:). In the window that appears, double click on the file index.html.
• Load Windows Explorer and locate index.html on the CD-ROM drive. Double click on this file.
After doing any one of the above, the file index.html should be loaded into Internet Explorer (or whatever web
browser is installed on your computer). Click on the link for COS112-V and follow the instructions.

Appendix A of this tutorial letter contains more instructions about the use of the C++ software.

4 Additional Reading
You do not have to consult any other textbooks apart from Savitch. However, some of you may want to read more
widely, and consult alternative references. The following useful books are available in the Unisa library. Please note
that the library does not have multiple copies of these books and that only limited waiting lists are kept.

DS Malik. C++ Programming: From Problem Analysis To Program Design. Course Technology, Thomson
Learning, 2009.

HM Deitel and PJ Deitel. C++ How to Program. 6 th edition. Prentice Hall, 2007.

John R. Hubbard. Programming with C++. 2 nd edition. Schaum’s Outlines, 2000.


7 COS112V/101/3/2009

5 Student Support
5.1 Communication with the University

Lecturers for this module are only responsible for content-related queries about the study material used for
COS112-V.

If you need to contact the University about matters not related to the content of this module, please consult the
publication Unisa: services and procedures that you received with your study material. This booklet contains
information on how to contact the University (e.g. to whom you can write for different queries, important telephone
and fax numbers, addresses and details of the times certain facilities are open).

NB: Always have your student number at hand when you contact the University.

Please note that all administrative enquiries should be directed to the Unisa Contact Centre. Enquiries will then be
channeled to the correct department. The details are as follows:

• Calls (RSA only) 0861 670 411


• International Calls +27 11 670 9000
• Fax number (RSA) 012 429 4150
• Fax number (international) +27 12 429 4150
• E-mail study-info@unisa.ac.za

5.2 Contacting the lecturers


The names of the lecturers will be announced in Tutorial Letter COSALLF/301/4/2009. You can contact us by mail,
e-mail, telephone or fax. If you write us a letter that you want us to reply to, please include your name, student
number and postal address.

The School of Computing can be contacted telephonically at (012) 429 6122. Should you be unable to reach any
of the lecturers for COS112V, please leave a message with one of the secretaries, who can be contacted via the
number given above. Remember to include the module code and your student number with the message.

E-mail queries should be sent to cos112@osprey.unisa.ac.za, and not directly to a lecturer. Please supply your
full name, student number, as well as the module code in your e-mail. The mail will be forwarded to the lecturer
responsible for e-mail correspondence at that particular time. This is why you need to supply the module code.

Content-related queries should be posted on the COS112V discussion forum, which is discussed below, rather than
sent to the COS112V e-mail address. However, if you do not have access to the Internet, you are welcome to send
your query by mail - we will then post it on the COS112V discussion forum on your behalf, and send you a copy of
the reply we (or a fellow student) gave on the discussion forum.

5.3 The COS112-V home page


The School of Computing has its own web site at http://osprey.unisa.ac.za. Follow the links from there and read the
instructions on personalising the web interface according to your modules. Please read Tutorial Letter
COSALLF/301/4/2009 for more information on the web site.
8

Visit the COS112V home page frequently for new information during the course of your studies. All the COS112V
tutorial letters will be made available on the COS112V home page. In particular, the solutions to the assignments
will be available about one to two weeks after the respective due dates.

In addition to the study material, the Osprey home page also has links to discussion forums that allow you to
communicate with the lecturers and your fellow students. Content-related queries and comments should be posted on
the discussion forum, and not sent to the module e-mail address. If no-one else responds adequately, one of the
lecturers will. In this way, instead of responding fifty times to the same question, five hundred students may benefit
from a single reply. The lecturers will monitor the forum, but only respond if they deem it necessary.

Unlike the case when contacting us by e-mail, you are welcome to remain anonymous when posting queries on the
discussion forum - your e-mail identity will be known to the lecturers, but it will appear scrambled in the posting.
You can choose how you want to identify yourself in the discussion forum.

5.4 myUnisa
Unisa also has a web site called myUnisa which you can use to access resources and information at the
university. The myUnisa learning management system is Unisa's online campus that will help you to
communicate with your lecturers, with other students and with the administrative departments of Unisa through
the internet. You can also use myUnisa to submit your assignments and check whether they have been received
and marked.

To go to the myUnisa website, start at the main Unisa website, http://www.unisa.ac.za, and then click on the
“Login to myUnisa” link on the right-hand side of the screen. This should take you to the myUnisa website. You
can also go there directly by typing in http://my.unisa.ac.za.

Please consult the publication Unisa: services and procedures which you received with your study material for
more information on myUnisa.

5.5 Student support systems


For more information on the various student support systems and services available at Unisa (e.g. student
counselling, tutorial classes, language support), please consult the publication Unisa: services and procedures that
you received with your study material.

5.6 Study groups


It is advisable to have contact with fellow students. One way to do this is to form study groups. The addresses of
students in your area may be obtained from the following department:

Directorate: Student Administration and Registration


PO Box 392
UNISA
0003

Please contact the Unisa Contact Centre 086 167 0411.


9 COS112V/101/3/2009

6 Study Programme
6.1 Syllabus
In this module we cover the following chapters of Savitch:

Chapter Sections covered

Chapter 1 1.1 and 1.2

Chapter 4 Only 4.6

Chapter 5 Only 5.5

Chapter 6 All sections

Chapter 8 8.1 and 8.3, plus the subsection on page 483 (Converting Between
string Objects and C Strings), thus excluding 8.2 with the
exception of the subsection on page 511

Chapter 9 All sections excluding the optional subsections in 9.2

Chapter 10 All sections

Chapter 11 All sections, plus Appendixes 7 (p 1044) and 8 (p 1047)

Chapter 12 12.1 and 12.2 up to page 743, thus only the first two pages of 12.2

Chapter 14 14.1 and 14.2 up to page 831, thus excluding 14.3

Chapter 15 Only 15.1, thus excluding 15.2 and 15.3

Chapter 17 All sections

Note that some of the sections (in Chapters 1, 4 and 5) are omitted, because they have already been covered in
COS111U. The other sections that are omitted fall outside the scope of this module.

6.2 Practical work


All COS112V students must have access to a computer running Windows. The computer must have a CD-ROM
drive. Note, however, that we do not support Windows Vista. For the purposes of students who have to or wish to
use Windows Vista, we include instructions on installing the prescribed software on Windows Vista in Appendix B.

All the assignments require extensive practical work on a computer. The examination is a purely written examination
and does not involve doing any work on the computer. There are no compulsory separate practicals that students
need to attend during the year, but a practical workshop will be offered during March (first semester registrations)
and August/September (second semester registrations). You will receive more information on this at a later stage.
10

If you do not have a computer at home, gain access to one somewhere else, possibly at work, at a friend’s home, or at
one of Unisa’s computer laboratories. The Unisa computer laboratories in Pretoria and at the regional offices are
available to students for the practical work. You will receive a COSALL tutorial letter explaining where the
laboratories are, the hours during which they are open and the booking procedure.

6.3 Planning your academic year


In overview, the undergraduate academic year is as follows:
First semester Second semester
19 January Academic year begins 13 July Academic year begins

13 February First assignment due 7 August First assignment due

20 March Second assignment due 11 September Second assignment due

May/June Examinations November Examinations

To get going with your studies, do the following:


• Read this tutorial letter (COS112V/101/3/2009) and Tutorial Letter COSALLF/301/4/2009.
• Obtain a copy of the prescribed book.
• Arrange for access to a computer.
• Install the software, referring to Appendix A of this tutorial letter.

We provide two study programmes, one for students who registered for the first semester, and one for students who
registered for the second semester. We recommend that you use the study programmes as a starting point. You will
probably need to adapt this schedule, taking into account your other modules and your personal circumstances. For
example, if the postal service is slow, you may have to move these dates forward.

Study programme for first semester registration:


Week Date (Monday) Activity Remark
1 19 Januarie 2009 Install software, Queries on software installation will only be
Study sections in answered up to 31 January
chapters 1, 4 and 5
2 26 Januarie 2009 Study chapter 6
3 2 February 2009 Study chapter 9
4 9 February 2009 Do assignment 1 Due date 13 February 2009
5 16 February 2009 Study chapter 10
6 23 February 2009 Study chapter 11
7 2 March 2009 Study chapter 12
8 9 March 2009 Attend workshop Otherwise, attempt workshop on your own
9 16 March 2009 Do assignment 2 Due date 20 March 2009
10 23 March 2009 Study chapter 8
11 30 March 2009 Study chapter 14
12 6 April 2009 Study chapter 15
13 13 April 2009 Study chapter 17
13 20 April 2009 Do assignment 3 Self-assessment
14 27 April 2009 Revision Study all tutorial matter, including solutions to
15 4 May 2009, up to Revision assignments and workshop. Do examination
examination date paper supplied in examination tutorial letter on
paper.
11 COS112V/101/3/2009

Study programme for second semester registration:


Week Date (Monday) Activity Remark
1 13 July 2009 Install software, Queries on software installation will only be
Study sections in answered up to 31 July
chapters 1, 4 and 5
2 20 July 2009 Study chapter 6
3 27 July 2009 Study chapter 9
4 3 August 2009 Do assignment 1 Due date 7 August 2009
5 10 August 2009 Study chapter 10
6 17 August 2009 Study chapter 11
7 24 August 2009 Study chapter 12
8 31 August 2009 Attend workshop Otherwise, attempt workshop on your own
9 7 September 2009 Do assignment 2 Due date 11 September 2009
10 14 September 2009 Study chapter 8
11 21 September 2009 Study chapter 14
12 28 September 2009 Study chapter 15
13 5 October 2009 Study chapter 17
13 12 October 2009 Do assignment 3 Self-assessment
14 19 October 2009 Revision Study all tutorial matter, including solutions to
15 26 October 2009, up Revision assignments and workshop. Do examination
to examination date paper supplied in examination tutorial letter on
paper.

6.4 Hints on studying this module

Study each chapter in the prescribed book by following these steps:


• Read the corresponding discussion given in the study guide, Tutorial Letter COS112V/501/3/2009.
• Scan the chapter in Savitch to get an overview of what the chapter is about.
• Read the chapter again, making sure that you process the information. Relate the text to the given program
listings. You will sometimes have to read a little ahead or read a whole section to make meaningful sense of
a program listing or discussion. Many students merely read the code and not the accompanying text that
explains the code.
• Take the source listing of the sample programs in the textbook, type it into a text file, compile it and execute
it. Observe the output produced. Some of the source listings of the examples can be found on the CD that
you received with your textbook. Appendix C contains instructions on how to gain access to the source
listings.
• Do as many as possible of the self-check questions on a section as you study it. Answers to the self-check
questions are available at the end of each chapter.
• Answer the assignment questions on the chapter. Implement all programming questions on your computer.

It is important to realise that the process of learning how to program follows a learning curve: The more programs
you write, the more proficient you will become. Remember that COS112V has a large practical component and that
it is essential to gain a lot of programming experience. Programming modules also require much more time than
other modules with no practical work. You will probably find that you need to work hard and consistently
throughout the year to develop the necessary programming skills. Plan to spend at least 8 hours per week on this
module.
12

7 Examination
7.1 Examination Admission
Due to regulatory requirements imposed by the Department of National Education the following applies:

To be considered for examination admission in COS112V, a student must submit assignment 1 BEFORE 27
February 2009 (first semester registration) or 21 August (second semester registration). Please keep a copy of
the completed compulsory assignment you submit, so that you have the necessary proof in the event that the
assignment is lost before it can be assessed.

You are expected to submit two assignments during the semester. Since the work in COS112V is progressive and
later sections build on earlier ones, we suggest that you begin studying as soon as possible and that you do all the
assignments in their proper sequence. Do not leave an assignment until the last minute. You are expected to work
throughout the semester, and falling ill the day before a due date is no excuse not to hand in an assignment. By that
time, you should have completed at least 80% of the assignment, which you should hand in without delay. Due to the
time constraints of the semester system, we cannot extend any submission dates for assignments. The
assignments play an important role in assisting you to master the study material, and also contribute to your year
mark. See section 6.3 for more on the year mark.

Examination admission is finalised during April (first semester) and September.(second semester). You will soon
receive an examination tutorial letter giving more information on the format of the examination paper.

7.2 Examination period


This module is offered in a semester period of fifteen weeks. This means that if you are registered for the first
semester, you will write the examination in May/ June 2009 and the supplementary examination will be written in
October/ November 2009. If you are registered for the second semester you will write the examination in October/
November 2009 and the supplementary examination will be written in May/ June 2010.

During the module (of the semester), the Examination Section will provide you with information regarding the
examination in general, examination venues, examination dates and examination times.

Make a note of your examination dates and arrange with your employer for leave in good time. Check for clashes on
the examination time-table and, should there be any, discuss them with the Examinations Department immediately.

7.3 Year mark


The mark you obtain for assignments will contribute to a year mark. The year mark in turn will contribute 10% of
the final mark you will receive for COS112-V, while the mark you obtain in the examination will contribute the
remaining 90% of your final mark.

The weights allocated to the assignments for COS112-V are summarized as follows:

Assignment number Weight


1 (compulsory) 20%
2 80%
3 0% (self-
assessment)

To explain how this will work, assume that a student receives 75% for assignment 1, and 80% for assignment 2.
His/her year mark will then be calculated as follows:
13 COS112V/101/3/2009

Assignment Mark received Weight Contribution to year mark


(Percentage) Mark(%) * Weight(%) Contribution
1 75% 20% 75/100 * 20/100 0.15
2 80% 80% 80/100*80/100 0.64
Total: 0.79

When the total of 0.79 is converted to 10% of the final mark, it will be 7.9%, thus the student’s year mark will be
7.9%. The examination will form the remaining 90% of the final mark for the module. Note that the year mark will
not form part of the final mark for the supplementary examination.

8 The Assignments
Assignments are seen as part of the learning material for this module. As you do the assignment, study the reading
texts, consult other resources, discuss the work with fellow students or tutors or do research, you are actively
engaged in learning. Looking at the assessment criteria given for each assignment will help you to understand what is
required of you more clearly.

Two sets of assignments for this year are given at the end of this tutorial letter. The first set of assignments have to
be submitted by students registered for the first semester, and the second set of assignments have to be submitted by
students registered for the second semester. The tutorial matter you have to master in order to complete each
assignment appears in the study programme in Section 6 and at the start of each assignment. The study guide,
Tutorial Letter 501, contains details on each section. Give yourself enough time to do the assignments properly,
bearing in mind that a single session in front of the computer will not be sufficient to complete a programming task.

The time constraints under the semester system do not allow us to accept late assignments.

All the assignments require practical work, i.e. programs that you have to implement on your computer. Submit a
printout of each program, as well as the input and corresponding output for the program. Assignments1 and 2 have to
be submitted by the due date. Assignment 3 is for self-assessment, i.e. you do not have to submit it to Unisa, but will
‘mark’ it yourself by comparing your attempt with the model solution.

PLEASE ADHERE STRICTLY TO THE FOLLOWING RULES:

• Submit only one copy of a specific assignment.


• Use the correct assignment number on your assignment cover, or on myUnisa if you submit your
assignments electronically.
• Do not send assignments directly to any of the lecturers or to the COS112V e-mail address.
• Assignments must reach UNISA by the due date.
• Check on myUnisa, or contact the Assignments Section to ensure that your assignment was received by
UNISA.
• All programs must be implemented on a computer. Hand-written programs will not be marked. Copy
your programs and output to one word-processing document before you submit.
• NO floppies, stiffies or CDs will be accepted!
• Assignments may not be submitted by fax or e-mail.

PLEASE NOTE: Enquiries about assignments (e.g. whether or not the University has received your
assignment or the date on which an assignment was returned to you) must be
addressed to the Unisa Contact Centre at 0861 670 411 (RSA only), or +27 11 670 9000
(international calls) (also see par. 3 above). You might also find information on
myUnisa.
14

Assignments should be addressed to:

The Registrar
PO Box 392
UNISA
0003

You may submit written assignments and assignments either by post or electronically via myUnisa. Follow the
instructions given in Tutorial Letter COSALLF/301/4/2009, as well as the brochure Unisa: services and procedures,
when submitting your assignments. The URL for myUnisa is: http://my.unisa.ac.za/. Instructions on how to register
to become a myUnisa user, and how you should format your assignments before you submit them electronically, are
given on the web site. The two most important things to remember are that your submission must consist of a single
text file, and that you may submit an assignment only once.

The process to submit an assignment via myUnisa is briefly described below:


• Go to myUnisa at http://my.unisa.ac.za/.
• Log on with your student number and password.
• Choose the correct module (COS112V) in the orange block.
• Click on assignments in the menu on the left-hand.
• Click on the assignment number for the assignment that you want to submit.
• Follow the instructions.

You will receive tutorial letters (201 and 202) discussing each assignment. The solution to assignment 3 is provided
in Appendix D of this tutorial letter. Work through the solutions and make sure that you understand them. When you
receive your marked assignment back from Unisa, compare it to our solutions and make sure you understand the
differences, and also why you lost marks. The assignments serve a very important learning function. Therefore,
even if you do not submit a particular assignment, you should still complete it and compare your solution to ours as
part of your study programme.

We may mark only selected questions in the assignment and not the entire assignment. However, as mentioned
before, we discuss each assignment question in a detailed tutorial letter that you will receive after the due date.

You are welcome to work in small groups. However, every member of the group must write and submit his or her
own individual assignment. Thus, discuss the problem, find solutions, etc. in the group, but then do your own
programming and submit your own effort. You will learn to program only if you sit down in front of the computer,
type in the code, debug the program and get it to work. It is unacceptable for students to submit identical
assignments on the basis that they worked together. That is copying (a form of plagiarism) and none of these
assignments will be marked. It is dishonest to submit the work of someone else as your own, i.e. to commit
plagiarism. Such unethical behaviour does not become our profession.

Plagiarism is the act of taking words, ideas and thoughts of others and passing them off as your own. It is a
form of theft which involves a number of dishonest academic activities. Furthermore, you may be penalised or
subjected to disciplinary proceedings by the University.

The Disciplinary Code for Students (2004) is given to all students at registration. Students are advised to study
the Code, especially Sections 2.1.13 and 2.1.4 (2004:3-4). Kindly read the University’s Policy on Copyright
Infringement and Plagiarism as well.
15 COS112V/101/3/2009

Assignment 1 (First Semester)


DUE DATE: 13 February 2009

TUTORIAL MATTER: Chapters 4 to 7 and 9 of the Study Guide


Chapters 4 (section 4.6), 5 (section 5.5), 6 and 9
(excluding the optional parts of section 9.2) of Savitch

WEIGHT: 20%

EXTENSION: None

Answer all the questions. Submit all the programs you are required to write, as well as the input and output of all
programs.

Copy the programs and the required input and output to ONE word processor file.
WE DO NOT ACCEPT ANY FLOPPIES, STIFFIES OR CDs.

Question 1

Write a program to determine the weekly pay for an employee. The program should use two overloaded
functions, each named calcWeeklyPay, to determine the weekly pay for an employee. Salaried employees
receive their annual salary divided by 52 (the number of weeks per year) per week, while hourly paid employees
receive the hourly pay-rate multiplied by the number of hours worked during the week. One of the overloaded
functions should accept the annual salary as argument, while the other function accepts arguments for the hourly
rate and the number of hours worked during the week. Both functions should return the weekly pay for the
employee.

Question 2
Write a program that converts from 24-hour notation to 12-hour notation. For example, it should convert 14:25
to 2:25 PM. The input is given as two integers. Verifies that a legitimate 24-hour notation has been input by
using the assert statement.

Question 3
For research purposes and to improve assistance to students, your university wants to know how well female and
male students perform in certain courses. You receive a file that contains female and male student examination
results. Due to confidentiality, the letter code f is used for female students and m for male students. Every file
entry consists of a letter code followed by an examination result. Each line has one entry. The number of entries
in the file is unknown. Write a program that computes and outputs the average examination result for both male
and female students. Prompt the user for the name of the file that contains the examination results that have to
be processed. The program should assert an error if the file contains no male students or no female students.
Write the output to a file report.txt.

For an input file with the following examination results:


m 56
f 78
f 44
m 48
16

m 57
f 59
m 65

the corresponding output file report.txt should be:


Average exam score for males: 56
Average exam score for females: 60

Question 4

Write a program that copies the characters in an input file to an output file except for the digit characters. For a
digit character the program instead writes the digit’s name; that is, ‘zero’ for 0, ‘one’ for 1, and so on.

Question 5
(a) For each of the following, write a single C++ statement that performs the indicated task. Assume that
integer variable counter has been declared

i. Declare two variables IntPtr1 and IntPtr2 to be pointers to objects of type int. Do this in two
different ways.
ii. Let the pointer IntPtr1 point to the integer object counter.
iii. Print the address stored in IntPtr1.
iv. Let Intptr2 point to a new, nameless variable and initialise it to 15.
v. Copy the value pointed to by pointer IntPtr1 to the memory location pointed to by pointer IntPtr2.
vi. Let the pointer IntPtr2 point to the same location as the pointer IntPtr1.
vii. Print the value of the object pointed to by pointer variable IntPtr1.
viii. Release the memory location to which IntPtr1 points to the freestore memory.

(b) Use diagrams similar to display 9.1 on p 534 in Savitch to trace the following program and give the output
of the following program.

#include <iostream>
int main()
{
int value1 = 10;
int value2 = 40;
int *ptr1 = &value1;
int *ptr2 = &value2;
ptr1 = ptr2;
cout << *ptr1 << endl;
cout << *ptr2 << endl;
return 0;
}
17 COS112V/101/3/2009

Assignment 2 (First semester)


DUE DATE: 20 March 2009

TUTORIAL MATTER: Chapters 10, 11 and 12 of the Study Guide


Chapters 10, 11 and 12 (excluding pages 700 to 712) of
Savitch
Appendices 7 and 8 in Savitch

EXTENTION:
None

WEIGHT: 80%

Answer all the questions. Submit all the programs you are required to write, as well as the input and output of all
programs.

Copy the programs and the required input and output to ONE word processor file.
WE DO NOT ACCEPT ANY FLOPPIES, STIFFIES OR CDs.

Question 1

Consider the following structure used to keep record of a student’s scores:


struct Student
{
string name;
int quiz1;
int quiz2;
int midtermExam;
int finalExam;
}

A student is graded according to the following policies:


The two quizzes are each graded on the basis of 10 points.
The midterm exam and the final exam are each graded on the basis of 100 points.
The final exam counts for 50% of the grade, the midterm counts for 25%, and the two quizzes together count for
a total of 25%. (Do not forget to normalize the quiz scores. They should be converted to a percentage before they
are averaged in.)

Turn the student record into a class type rather than a structure type. The student record class should have
member variables for all the input data. Make all member variables private. Include public member
functions for each of the following:
a default constructor that sets the student ‘s name to a blank string, and all the scores to 0;
member functions to set each of the member variables to a value given as an argument to the function (i.e.
mutators);
member functions to retrieve the data from each of the member variables (i.e. accessors);
and a function that calculates and returns the student’s weighted average numeric score for the entire course.

Use this class in program which grades a student. The program should read in the student’s name and scores and
output the student’s record as well as the student’s average numeric score for the entire course. Use the keyboard
to supply input and display the output on the screen. Test your program with the following input:

Student name: Johnny Applemac


18

Quiz 1: 7
Quiz 2: 5
Midterm exam: 65
Final exam: 73

Question 2
The questions below refer to the following class declaration and partial implementation:

#include <iostream>
#include <string>
using namespace std;

class personType {
public:
personType();
personType(string name);
void setfirstName(string name);
void setlastName(string name);
string getfirstName() const;
string getlastName() const;
bool checkName(string name) const;
private:
string firstName; //store the first name
string lastName; //store the last name
}

personType::personType() {
firstName = “”;
lastName = “”;
}

void personType::setlastName(string name) {


int len = name.length();
int blankpos = name.find(“ ”,0);
lastName = name.substr(blankpos+1, len);
}

void personType::setfirstName(string name) {


int blankpos = name.find(“ ”,0);
firstName = name.substr(0,blankpos);
}

(a) What is the purpose of the keywords public and private in the class declaration?
(b) What is the purpose of a constructor?
(c) Is setlastName() an accessor or mutator? Explain your answer.
(d) Implement the second (overloaded) constructor of the personType class.
(e) Implement the getlastName() member function. The function should return the last name of the
person.
(f) Overload the stream insertion operator as a friend operator. It should write the person’s first name and last
name to the given output stream.
(g) Implement the checkName() member function. This function should determine whether a given name
(first name and last name) is the same as the name (first name and last name) of this person.
19 COS112V/101/3/2009

Question 3
Define a class for complex numbers. A complex number is a number of the form
a + b*i
where, for our purposes, a and b are numbers of type double, and i is a number that represents the quantity
− 1 . Represent a complex number as two values of type double. Name the member variables real and
imaginary. (The member variable for the number that is multiplied by i is the one called imaginary.) Call
the class Complex.

Include three constructors:


a default constructor that initializes an object to 0 (that is, to 0 + 0*i).
a constructor with two parameters of type double that can be used to set the member variables of an object to
any values.
a constructor that has only a single parameter of type double; call this parameter real_part and define the
constructor so that the object will be initialised to real_part + 0*i.

Overload all of the following operators as friend functions so that they correctly apply to the type Complex: ==,
+, -, *, >> and <<. You should write a test program to test your class.

Hints:
The ISO/ANSI C++ Standard says that the insertion operator and extraction operator for complex numbers
should read and write complex numbers of the form: re, (re), or (re, im), where re is the real part and
im is the imaginary part. For the purpose of this class, we only read and write a complex number of the form
(re,im), i.e. the complex number 1 + 2*i should be read and written as (1,2) by your class.
Two complex numbers are equal when the real parts of the two complex numbers and the imaginary parts of the
two complex numbers are the same.
To add or subtract two complex numbers, you add or subtract the two member variables of type double.
Therefore the following equations can be used to add or subtract two complex numbers:
Addtion: (a + b*i) + (c + d*i) = (a + c) + (b + d)*i
Subtraction: (a + b*i) - (c + d*i) = (a - c) + (b - d)*i
The product of two complex numbers is given by the following formula:
(a + b*i) * (c + d*i) = (a*c – b*d) + (a*d + b*c)*i

Question 4
Overload the +, - and * operators for objects of class Complex in question 3, as member functions. Use the
same program as in question 3 to test these member functions.

Question 5
Turn the Complex class from question 4 in this assignment into an ADT, so that separate files are used for the
interface and implementation. Use separate compilation to compile the implementation separate from the
application program that tests the ADT.

Question 6
Overload the stream extraction operator >> for the class Student in Question 1 to read values for each member
variable from a file. Also overload the stream insertion operator << to print the record for a student (name, two
quiz scores, midterm score and final exam score) as well as the weighted average for the student either on the
screen or to a file.

Use separate compilation and write a program that uses the overloaded extraction operator >> to read records for
students from a file named Student.dat into an array. Assume that the file will never contain data for more
20

than 20 students. Use the array to determine the weighted average for each student, as well as the average for all
of the students (i.e. the class average). Display the output on the screen. Use the following data:
Peter Pan 5 3 45 51
Wendy Hill 7 5 63 58
Alice Mokgaba 8 6 51 67
Precious Petersen 5 7 49 46
Thumi Tebogo 4 7 69 65
21 COS112V/101/3/2009

Assignment 3 (First Semester and Second Semester)


TUTORIAL MATTER: Chapters 8, 14, 15 and 17 of the Study Guide
Chapters 8, 14 (excluding section 14.3), 15 (excluding
sections 15.2 and 15.3) and 17 of Savitch

WEIGHT: None

This assignment is for self-assessment. Do not submit this assignment. The solution to this assignment appears in
Appendix D of this tutorial letter.

Question 1
Write a program that inputs two C string variables, first and last, each of which the user should enter with his
or her name. First, convert both C strings to lowercase. Your program should then create a new C string that contains
the full name in pig latin with the first letter capitalized for the first and last name. The rules to convert a word into
pig latin are as follows:
If the first letter is a consonant, move it to the end and add "ay" to the end.
If the first letter is a vowel, add "way to the end.
For example, if the user inputs "Erin" for the first name and "Jones" for the last name, then the program should create
a new string with the text "Erinway Onesjay" and print it.

Question 2

(a) Write a sorting function that is similar to Display 7.12 in Chapter 7 in Savitch, except that it has an argument for
a vector of ints rather than an array. This function will not need a parameter like number_used as in
Display 7.12, since a vector can determine the number used with the member function size(). This sort
function will have only this one parameter, which will be of a vector type. Use the selection sort algorithm
(which was used in Display 7.12).

(b) Write a program that reads in a list of integers into a vector with base type int. Provide the facility to either
read this vector from the keyboard or from a file, at the user's option. If the user chooses file input, the program
should request a file name. The output is to be a two-column list. The first column is a list of the distinct vector
elements; the second column is a count of the number of occurrences of each element. The list should be sorted
on entries in the first column, largest to smallest. Adapt the sorting function from (a) as necessary.

For example, for the input

-12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12


The output should be
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
22

Question 3

Write a recursive function that returns the sum of the integers between any two integer numbers inclusive. For
example if we want to calculate the sum of integers between the integer numbers 13 and 17 then the sum will be
13 + 14 + 15 + 16 + 17 = 75. This recursive function will expect two integer parameters and will return a double.

Question 4

Examine the code fragment below and answer the questions that follow:

1: #include <iostream>
2: using namespace std;
3:
4: //------------------------------------------
5:
6: class A
7: {
8: private:
9: int x;
10: protected:
11: int getX();
12: public:
13: void setX();
14: };
15:
16: int A::getX()
17: {
18: return x;
19: }
20:
21: void A::setX()
22: {
23: x=10;
24: }
25:
26: //----------------------------------------------
27: class B
28: {
29: private:
30: int y;
31: protected:
32: A objA;
33: int getY();
34: public:
23 COS112V/101/3/2009

35: void setY();


37: };
38:
39: void B::setY()
40: {
41: y=24;
42: int a = objA.getX();
43: }
44:
45: //----------------------------------------------
46:
47: class C: public A
48: {
49: protected:
50: int z;
51: public:
52: int getZ();
53: void setZ();
54: };
55:
56: int C::getZ()
57: {
58: return z;
59: }
60:
61: void C::setZ()
62: {
63: z=65;
64: }

Answer the following questions based on the code fragment given above:

(a) Is line 18 a valid access? Justify your answer.


(b) Is line 32 a valid statement? Justify your answer.
(c) Identify another invalid access statement in the code.
(d) Class C has public inheritance with the class A. Identify and list class C’s private, protected and public
member variables resulting from the inheritance.
(e) If class C had protected inheritance with the class A, identify and list class C’s private, protected and
public members variables resulting from the inheritance.
24

Question 5
Consider the class definitions below and answer the questions that follow:

class Date{
public:
friend ostream & operator<<(ostream & cout, const Date & d);
Date(int y, int m, int d);
private:
int year, month, day;
};

class Publication {
public:
Publication(const string & p, const Date & d,
const string & t);
Date GetDate( ) const;
string GetPublisher( )const;
string GetTitle() const;
private:
string publisher;
Date date;
string title;
};

(a) Implement the Date and the Publication classes.

(b) Code the interface of a derived class Book for which the Publication class is the base class. The Book
class has two additional member variables representing the ISBN number and the author of a book.
Furthermore, the Book class contains member functions getISBN( ) and getAuthor( ) that returns
the ISBN number and the author respectively. The declaration must also include a constructor for the class
Book.

(c) Implement the Book class.

(d) Recode the following interface such that class Magazine, derives from class Publication:
class Magazine{
public:
Magazine(const string & p, const Date & d, int ipy);
int GetIssuesPerYear( ) const;
Date getDate( ) const;
string getPublisher( )const
string GetTitle() const;
private:
int issuesPerYear;
string publisher;
Date date;
string title;
};

(e) Implement the Magazine class.

(f) In a driver program embed code to do the following:


(i) Declare an object B of type Book, with the following details:
publisher: FisherKing
date: 01/01/2000
title: Global Warming
25 COS112V/101/3/2009

isbn : 123456789
author: Ann Miller

(ii) Output all the details of Book B.

(iii) Declare an object M of type Magazine, with the following details:


publisher: Blue Marlin
date: 02/02/2005
title: The Earth and the Environment
number of issues per year: 12

(vi) Output all the details of Magazine M.

(g) Write a statement to overload operator<< as a friend function to the class Book and insert the
following implementation to your code:

ostream & operator<<(ostream & out, const Book & B)


{
out<<B.title<<endl;
out<<B.publisher<<endl;
out<<B.date<<endl;
out<<B.author<<endl;
out<<B.ISBN<<endl;
}

You should obtain the following compiler errors:

In function `std::ostream& operator<<(std::ostream&, const Book&)':


error: `std::string Publication::title' is private
error: `std::string Publication::publisher' is private
error: `Date Publication::date' is private

Suggest two ways to fix this compiler problem.

Question 6
Write a function template for a function that has parameters for a partially filled array and for a value of the base type
of the array. If the value is in the partially filled array, then the function returns the index of the first indexed
variable that contains the value. If the value is not in the array, the function returns -1. The base type of the array is
a type parameter. Notice that you need two parameters to give the partially filled array: one for the array and one for
the number of indexed variables used. Also write a suitable test program to test this function template.

Question 7
Write a template version of a search function for determining whether an array contains a particular value.

Question 8
Study the Matrix class interface and answer the questions that follow:
(Refer to the Notes at end of the question if you are unfamiliar with Matrices)

template<class Object>
class Matrix
{
public:
Matrix( int row = 0, int col = 0 );
26

void SetValue(Object value, int r, int c);


Object GetValue( int r, int c) const;
int GetRow() const;
int GetCol() const;
void OutPut(ostream & out) const;
private:
vector< vector<Object> > array;
int rows;
int cols;
};

(a) Complete the implementation of the Matrix class where indicated:

template <class Object>


Matrix<Object>::Matrix (int row, int col)
{ rows = row;
cols = col;
array.resize(row);
for (int r = 0; r < row; r++)
array[r].resize(col);

//SetValue assigns row r and column c of the Matrix to value


template <class Object>
void Matrix<Object>::SetValue(Object value, int r, int c)
{
//Complete code here
}

//GetValue returns the value in row r and col c of the Matrix


template <class Object>
Object Matrix<Object>::GetValue( int r, int c) const
{
//Complete code here
}

//GetRow returns rows


template<class Object>
int Matrix<Object>::GetRow() const
{
//Complete code here
}

//GetCol returns cols


template<class Object>
int Matrix<Object>::GetCol() const
{
//Complete code here
}

//Outputs the matrix in a tabular format (see Notes for example)


template <class Object>
void Matrix<Object>::OutPut(ostream & out) const
{
//Complete code here
}

//Operator+ is overloaded as a non-friend, non-member function. This //function adds two Matrices (see Notes
for example)
27 COS112V/101/3/2009

template<class Object>
Matrix<Object> operator+(const Matrix<Object> & x, const Matrix<Object> & y)
{
//Complete code here
}

b) Test your implementation by coding a main function to perform the following:


(i) Declare three, 2 by 2 integer matrices, M1, M2, and M3;
(ii) Store the following values in M1:
1 2
3 4
(iii) Store the following values in M2:
5 6
7 8
(iv) Store the sum of M1 and M2 in M3 using operator+.
(v) Output all three matrices.

Notes:
In mathematics, a matrix (plural matrices) is a rectangular table of numbers or, more generally, a table consisting
of abstract quantities that can be added and multiplied. For example, a 4 by 3 matrix is represented as:

6 6 6
5 3 2
3 1 2
2 7 9
Two matrices can be added if, and only if, they have the same dimensions. (That is, both matrices have matching
numbers of rows and columns.) We define their sum by constructing a third matrix whose entries are the sum of
the corresponding entries of the original two matrices. For example:

4 3 4 2 2 1 6 5 5
1 2 3 + 1 3 2 = 2 5 5
2 2 1 3 4 5 5 6 6
28

Assignment 1 (Second Semester)


DUE DATE: 7 August 2009

TUTORIAL MATTER: Chapters 4 to 7 and 9 of the Study Guide


Chapters 4 (section 4.6), 5 (section 5.5), 6, and 9
(excluding the optional parts of section 9.2) of Savitch

WEIGHT: 20%

EXTENSION: None

Answer all the questions. Submit all the programs you are required to write, as well as the input and output of all
programs.

Copy the programs and the required input and output to ONE word processor file.
WE DO NOT ACCEPT ANY FLOPPIES, STIFFIES OR CDs.

Question 1

Write a program to determine the tuition fees for a student. The program should use two overloaded functions,
each named calcFees, to determine the tuition fees for a student. Students who repeat a module pay a
different fee for the modules which are repeated. The program should first ask if the student repeats any
modules. If the student repeats, the program should ask for the number of modules which are repeated. One of
the overloaded functions should accept the number of modules enrolled for for the first time and the fee for those
modules as arguments, while the other function accepts arguments for the number of modules enrolled for for the
first time and the fee for those modules as well as the number of modules repeated and the fee for those modules.
Both functions should return the tuition fees for the student.

Question 2
The area of an arbitrary triangle can be computed using Hero’s formula for the area of a triangle:

area = sqrt(s(s - a)(s - b)(s - c))


where a, b, and c are the lengths of the sides, and s is the semiperimeter.

s = (a + b + c)/2
Write a void function that uses five parameters: three value parameters that provide the lengths of the sides, and
computes the area and perimeter or circumference (not the semiperimeter) via reference parameters. Make your
function robust by using the assert statement. Note that not all combinations of a, b and c produce a triangle.
Your function should produce correct results for legal data and reasonable results for illegal combinations.

Hint: The test for values of a, b and c to form a triangle is that each of the following inequalities be satisfied.
a + b > c
and
b + c > a
and
a +c > b
29 COS112V/101/3/2009

Question 3
Two data files are required to evaluate a multiple-choice examination. The first file (booklet.dat) contains the
correct answers. The total number of questions is 50. A sample file is given below:
ACBAADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD
The second file (answer.dat) contains the students’ answers. Each line has one student record that contains the
following information:
The student’s answers (a total of 50 answers): each answer can be A, B, C, D or * (to represent no answer).
There are no blanks between answers.
Student ID
Student name

A sample file is given below:


AACCBDBC*DBCBDAAABDBCBDBAA*BCBDD*BABDBCDAABDCBDBDA 6555 MAHMUT
CBBDBC*BDBDBDBABABABBBBBABBABBBBD*BBBCBBDBABBBDC** 6448 SINAN
ACB*ADDBCBDDAACDBACCABDCABCCBDDABCACABABABCBDBAABD 6559 CAGIL
Write a C++ program that counts the total number of correct answers by each student and outputs this information to
another file called report.dat. In this file, the students’ IDs, names and the scores must be given. Each correct
answer is worth 1 point.

For the sample files given above, the output should be as follows:
6555 MAHMUT 10
6448 SINAN 12
6550 CAGIL 49

Question 4
Write a program to number the lines found in a text file. The program reads text from a file and outputs each line
to the screen as well as to another file called Output.txt preceded by a line number. Print the line number at
the start of the line and right-adjusted in a field of three spaces. Follow the line number with a colon, then one
space, then the text of the line. You should get a character at a time, and write code to ignore leading blanks on
each line. You may assume that the lines are short enough to fit within a line on the screen. Obtain the name of
the input file from the user.

Using the following text for the input file:


Little Miss Muffet
Sat on a tuffet
Eating her curds and whey
Along came a spider
And chased her away

should produce the following output:


1: Little Miss Muffet
2: Sat on a tuffet
3: Eating her curds and whey
4: Along came a spider
5: And chased her away

Question 5
(a) For each of the following, write a single C++ statement that performs the indicated task. Assume that
integer variables counter and number have been declared and that number has been initialised to 7.
i. Declare two variables IntPtr1 and IntPtr2 to be pointers to objects of type int.
ii. Assign the address of variable number to pointer variable IntPtr2.
iii. Assign the value of the object pointed to by IntPtr2 to variable counter.
30

iv. Let the pointer IntPtr1 point to the same location as the pointer IntPtr2.
v. Let Intptr2 point to a new, nameless variable.
vi. Copy the value pointed to by pointer IntPtr1 to the memory location pointed to by pointer IntPtr2.
vii. Print the value of counter.
viii. Print the address of number.
ix. Print the address stored in IntPtr2. Is the value printed the same as the address of number?
x. Release the memory location to which IntPtr2 points to the freestore memory.

(b) Use diagrams similar to Display 9.1 on p 534 in Savitch to trace the following program and give the output
of the following program.

#include <iostream>
int main()
{
int value1 = 10;
int value2 = 30;
int *ptr1 = &value1;
int *ptr2 = &value2;
int *temp = p1;
ptr1 = ptr2;
ptr2 = temp;
cout << value1 << value2 << endl;
return 0;
}
31 COS112V/101/3/2009

Assignment 2 (Second Semester)


DUE DATE: 11 September 2009

TUTORIAL MATTER: Chapters 10, 11 and 12 of the Study Guide


Chapters 10, 11 and 12 (excluding pages 700 to 712) of
Savitch
Appendices 7 and 8 in Savitch

EXTENTION:
None

WEIGHT: 80%

Answer all the questions. Submit all the programs you are required to write, as well as the input and output of all
programs.

Copy the programs and the required input and output to ONE word processor file.
WE DO NOT ACCEPT ANY FLOPPIES, STIFFIES OR CDs.

Question 1
Consider the following structure used to keep record of a soccer player’s goals and the yellow or red cards he
received:
struct Player
{
string name;
int number;
int goals;
int cards;
}

Turn the soccer player’s record into a class type rather than a structure type. The soccer player record class should
have member variables for all the input data. Make all member variables private. Include public member functions
for each of the following:
• a default constructor that sets the soccer player‘s name to a blank string, and his number, the number of goals he
scored and the cards he received to 0;
• an overloaded constructor that sets the member variables to specified values;
• member functions to set each of the member variables to a value given as an argument to the function (i.e.
mutators);
• member functions to retrieve the data from each of the member variables (i.e accessors);
• an input member function with one formal parameter of type istream;
• and an output member function with one formal parameter of type ostream.

Embed your class definition in a test program.

Question 2
Create a class Fraction having two integer member variables named for a fraction’s numerator and denominator.
Ensure that you have three constructors:
• a constructor with two arguments that can be used to set the member variables of an object to any legitimate
values;
32

• a constructor with a single parameter of type int called whole_number so that the constructor initialises
the object to the fraction whole_number/1;
• a default constructor that initialises an object to 0 (that is 0/1).
The constructors must also prohibit a 0 denominator value.

Additionally, provide member functions for displaying an object’s data values.

Also provide the class with member functions add, sub, mul, and div that each carry out the operations +, -, *,
and /. For example, a + b will be written a.add(b) and a * b will be written a.mul(b).
Two Fraction objects are added, subtracted, multiplied and divided according to the following formulas:
a c ad + cb
Sum of two fractions: + =
b d bd
a c ad − cb
Difference of two fractions: - =
b d bd
a c ab
Product of two fractions: × =
b d bd
a c ad
Division of two fractions: ÷ =
b d cb

Include the class Fraction in a working C++ program that tests each of the class’s member functions.

Question 3
Include a member function named gcd() in the Fraction class that reduces a fraction to its lowest common
terms. Thus, a fraction such as 2/4 is reduced to ½. The means to do this is to divide both the numerator and the
denominator values by their greatest common divisor (GCD). A recursive definition to compute the GCD of two
integers follows:

n if n divides evenly in m
gcd(m,n) =
gcd(n, remainder of m divided by n) otherwise

This definition can be coded as follows:


int gcd(int m, int n)
{
if ((m % n) == 0)
return n;
else
return gcd(n, m % n);
}

Modify the constructor(s) written in the previous exercise to include a call to gcd() so that every initialized
fraction is in its lowest common terms. Also make sure that each overloaded operator function also uses gcd()
to return a fraction in lowest common terms.

Replace the display function with an overloaded insertion operator so that a Fraction object can be inserted
directly into the cout stream. Also include an overloaded extraction operator that uses the cin stream with a
Fraction object.

Question 4
Overload the +, -, * and / operators for objects of class Fraction in question 2, as friend functions. Use the same
program as in question 2 to test these member functions.
33 COS112V/101/3/2009

Question 5
Turn the Fraction class from question 4 in this assignment into an ADT, so that separate files are used for the
interface and implementation. Use separate compilation to compile the implementation separate from the
application program that tests the ADT.

Question 6
Overload the stream extraction operator >> for the class Player in Question 1 to read values for each member
variable from a file. Also overload the stream insertion operator << to print the record for a player (name,
number, goals and cards) either on the screen or to a file.

Use separate compilation and write a program that uses the overloaded extraction operator >> to read in records
for players from a file into an array. Assume that the file will never contain data for more than 20 players. Use
the array to determine the average score for a player, as well as the average number of cards for a player.
Display the output on the screen. Use the following data:
Pete Pannier 5 3 4
Lucas Radebe 7 5 0
Albert Mokgaba 8 0 0
Petrus Petersen 1 1 2
Thabelo Tebogo 4 0 3
Alex Qwela 2 1 3
Jonas Johnson 3 0 1
Gian Grooteboom 6 0 0
William Welman 9 1 4
Derrick Kabela 10 0 2
Martin Makgeba 11 2 1
34

Assignment 3 (Second semester )


See page 21 of this tutorial letter.
35 COS112V/101/3/2009

Appendix A: Installing the Software for COS112V


Contents
1. Software for COS112V ……………………………………………………………………….. 35
2. Installing the software …………………………………………………………………………. 36
3. Using the software……………………………………………….……………………………… 37
4. Separate Compilation: Creating DevC++ projects with multiple files ………………………… 41
5. Using the debugger in Dev-C++………………………………………………………………… 45
6. Printing …………………………………………………………………………………………. 48
7. Frequently Asked Questions ……………………………………………………………………. 49
8. CodeMate ………………………………………………………………………………………. 50

Dear Student
This appendix helps you to install and use the recommended software, namely the C++ Integrated Development
Environment (IDE). It covers installing the software, using the IDE and compiler, and some general comments
on troubleshooting some errors. The same instructions, except for section 4, can be found on your CD
DISK2009. It also contains some information regarding CodeMate, which is offered with the textbook.
Regards.
Your COS112V Lecturers

Note:
On registration you should receive the tutorial matter listed below:
DISK2008: Prescribed software
COS112V/101/2008: First tutorial letter: General information, study programme, exam admission and
assignments
COS112V/501/2008: The study guide

If you have not received all of the above mentioned tutorial matter, please contact our
DESPATCH DEPARTMENT via the Unisa Call Centre at 086 167 0411.

Note that all the COS112V tutorial letters will also be available on the Internet.

1. Software for COS112V


The first year C++ programming modules COS111U and COS112V both use the same prescribed software; a C++
compiler and an Integrated Development Environment (IDE).

The compiler you will be using for these modules is the MinGW port (version 5.0.0) of the Gnu Compiler
Collection (version 3.4.2). The MinGW compiler is designed to work on Windows 95/98/NT/2000/XP
platforms. Please note that Windows Vista is still an unstable operating system, and we cannot guarantee that the
MinGW compiler will work with it. If you want to try to use MinGW with Windows Vista, you will probably
have to ask the vendor who supplied you with Windows Vista to adjust the security settings to get it to work.

The MinGW compiler is distibruted under the GNU Public Licence, which means you are free to use, copy, sell
or modify the MinGW compiler. You are not required to register or pay for any of this software. (More
information on MinGW can be found at http://www.mingw.org/).

To access the compiler, you will be using an IDE called Dev-C++ (version 4.9.8.3). Neither the creators of Dev-
C++, nor ourselves, require you to pay for it. (See http://www.bloodshed.net/ if you want more information.)

Please note that you will probably also have problems installing and running Dev-C++ under Windows Vista.
We will not be able to assist you if you attempt to use the prescribed software with Windows Vista.
36

In COS112V you will be writing more complicated programs than in COS111U. In particular, later in the course
you will have to write programs that consist of more than one file. To be able to work with more than one file in
Dev-C++, you have to create a project. The Using the software instructions (section 3) therefore explain how to
create a project, and how to make sure that all the files are part of it.

Apart from the compiler and the IDE, we have included other useful software and documentation on the CD-Rom.
General purpose utility software (WinZip, Adobe Reader etc.) is in the \utils folder. Extra programming software,
IDEs, sources etc. are in the \src folder. The Dev-C++ help system contains help for Dev-C++. We have added links
to general C++ help. There is also some additional documentation in the \docs folder of the CD-Rom.

We are indebted to Bjarne Stroustrup for a number of his publications on C++. We also thank all of the many
contributors to all of the open source software on the CD-Rom.

2. Installing the software


For COS112, you will need the Dev-C++ IDE and the MinGW compiler. (This is exactly the same software as for
COS111. If you installed the software for COS111 this year, you need not do so again for COS112. If you installed a
previous version of the IDE and compiler last year, you should uninstall it, and reinstall the new version.) We give
two methods for doing this.

Method 1
Insert the CD into the CD drive and navigate to the CD drive using "Windows Explorer".
Double click on "Index.html" and then click on the second left-hand link “COS112-V”.
Then click on the link on the left-hand side called ”2. Installing the software”.
To install the MinGW compiler, follow the blue link “here” in the sentence “To install the MinGW compiler, click
here.“ by clicking on it.
A window will appear containing an icon for the MinGW setup called mingw_gcc3.4.2.exe. Double-click the file /
icon and follow the instructions after that.

During installation, you will be asked to choose the Destination Directory where you want MinGW to be installed.
We recommend that you accept the default destination directory, namely c:\unisa\mingw. If you choose anything
else, you will have to change some settings (Compiler Options) in Dev-C++ which expects the compiler to be stored
in a particular folder.

To install the Dev-C++ IDE, follow the blue link “here” in the sentence “To install the Dev-C++ IDE, click here.” by
clicking on it.

A window will appear containing an icon for the Dev-C++ setup. Double-click the icon and follow the instructions
after that.

During the installation, you will be asked to specify the Destination Directory where you want Dev-C++ to be
installed. We recommend that you choose the default, namely c:\unisa\devcpp.

Method 2
To install the MinGW compiler, do the following:

• Double-click on the "My Computer" icon on your desktop

• Right-click on your CD-Rom icon, and select "Explore";

• Navigate to the \install\mingw folder

• Double-click on the file mingw_gcc3.4.2.exe


During installation, you will be asked to choose the Destination Directory where the compiler must be installed. We
37 COS112V/101/3/2009

recommend that you accept the default destination directory, namely c:\unisa\mingw.
Then to install the Dev-C++ IDE:

• Navigate to the \install\devcpp folder

• Double-click on the file devcppsetup.exe


During the installation, you will be asked to specify the Destination Directory where you want Dev-C++ to be
installed. We recommend that you choose the default, namely c:\unisa\devcpp.
Uninstalling
To uninstall either the compiler or the IDE, use the Add/Remove Programs facility in the Control Panel of
Windows.

3. Using the software


Dev-C++ provides a friendly user interface to the MinGW C++ compiler. In fact, it will not be necessary for you to
work directly with the compiler. You can always do so by means of Dev-C++.

To help you get started we present a short guide to your first "Hello World" program.

As stated in section 1, Software for COS112V, we will be using projects in COS112 to allow us to write more
complicated programs consisting of more than one file. Although you will only need to write programs consisting of
more files later in the year, we recommend that you always create a project for your COS112 programs.

Step 1. Starting Dev-C++


During installation, a shortcut to Dev-C++ should have been placed on the desktop. Double-click it to start Dev-C++.
Otherwise, you can click on the Windows "Start" button and choose "Bloodshed Dev-C++" on the "Programs"
submenu. Alternatively, you can navigate to the folder C:\unisa\devcpp and execute the file devcpp.exe

Step 2. Setting the options


The first time you use Dev-C++, you will be required to choose the language and the user interface theme. We
suggest that you click on OK for each of these options to accept the defaults.
Before you use Dev-C++ to write your first program, you MUST change some of the settings to get it to work
properly:

• Choose "Compiler Options" on the "Tools" menu and click on the "Directories" tab.

• Under the "Binaries" subtab, the path C:\unisa\mingw\bin should appear. If there is some other path
specified, click on the "Delete Invalid" button. Either type the correct path in the edit box at the bottom of
the window, or choose it by clicking on the "..." browse button. Then click on the "Add" button to transfer
the path from the edit box to the list under "Binaries".

• Under the "Libraries" subtab, the path C:\unisa\mingw\lib should appear. If it isn't there, follow the above
instructions to fix it.

• Under the "C Includes" subtab, the path C:\unisa\mingw\include should appear. If it isn't there, follow the
above instructions to fix it.

• Under the "C++ Includes" subtab, no paths should appear. If any are listed, click on the "Delete Invalid"
button.

• Finally, click on the "Programs" tab (at the top of the window). Change the program for "make:" to
mingw32-make.exe. (It must not be gmake.exe.)
You only need to perform the above steps once. You are now ready to write your first C++ program!
38

Step 3. Creating a project


Always start your work by creating a new project. Click on "New | Project" on the "File" menu, or click on the "New
Project" toolbar button. You will be presented dialog with a number of project templates. Click on Console
Application and give a name for your project (eg. First).

After clicking on "OK", you will be required to specify where you want to save the project. We suggest that you
create a separate directory (such as c:\unisa\cos112) in which you save all your work for a particular module.
Navigate to this folder (if necessary) before clicking on the "Save" button.

Step 4. Editing a C++ source file


When you create a project as explained above, Dev-C++ automatically produces a source file from a template and
opens if for you to edit. Note the Project Browser panel on the left. You can click on the little plus sign next to the
project icon to see what files have been added to the project.

Initially the source file is called Untitled1, so the first thing you should do is give it a name. Do this by choosing
39 COS112V/101/3/2009

"Save" or "Save As" on the "File" menu or by clicking on the "Save" toolbar button. Type the name of the source
code file, eg. first.cpp. (Note that we are using the same name for the project and the source file. The names need not
be the same, however. Later, when you create projects that use multiple files, you will have to use different names.)
Now edit the program to look as follows:

Once you have edited the program, you can save it again by choosing "Save" on the "File" menu or by clicking on
the "Save" toolbar button.

Step 5. Compiling the program


Choose "Compile" on the "Execute" menu or click on the "Compile" toolbar button. A Compile Progress dialog will
be displayed:

Assuming you haven't made any typing mistakes, your program should compile without any errors. If compilation is
successful, the "Cancel" button will change to "Close". Click on the "Close" button. (If there are errors, a Compiler
Output panel will be displayed below the code editor specifying the errors that need to be fixed. See
Troubleshooting below if you are sure there isn't a mistake in your program, but it won't compile correctly.)
40

Step 6. Running the program


Either choose "Run" from the "Execute" menu or simply click on the "Run" toolbar button. If all goes well you
should see a window like the one below. (If you don't see the console window because it flashes and disappears,
choose "Environment Options" on the "Tools" menu and make sure "Console window remains open" is selected.
Then run the program again.)

To return to Dev-C++, press any key.

To create a new program, close your existing project, and open a new one. You should always select Console
Application as the type of project. Windows Applications and Static Libraries are not covered in COS112.

Troubleshooting
If your C++ project won't compile, check the following:

Check that Dev-C++ knows where the MinGW compiler is. In particular, check the following in "Tools | Compiler
Options" under the "Directories" tab:

• C:\unisa\mingw\bin should be added to "Binaries".

• C:\unisa\mingw\lib should be added to "Libraries".

• C:\unisa\mingw\include should be added to "C Includes".

• "C++ Includes" should be empty.


Note that if you installed the MinGW compiler in a directory other than the default (i.e. not in C:\unisa\mingw) then
you will have to change these paths accordingly.
Also check that the correct make program is being used: Click on "Tools | Compiler Options" and then on the
"Programs" tab. Make sure that mingw32-make.exe is specified as the make program (and not gmake.exe).

If you get an error of this type:


C:\unisa\xxxx\Makefile.win [Build Error] * [xxx_private.res] Error 1
during make, retry the make/compile again and the error should disappear.
41 COS112V/101/3/2009

4. Separate Compilation: Creating Dev-C++ Projects with


Multiple Files
This section refers to chapter 12 in the prescribed textbook and chapter 12 in Tutorial Letter 501. Separate
compilation is used to divide a program into parts that are kept in separate files, compiled separately and then
linked together when the program is run. It is typically used to separate the interface and implementation files of
a class. This section describes how to use the DevC++ IDE to set up a project with multiple files, compile and
use these files. We show how to set up a project that uses a user-defined class called TimeType. The class
TimeType will be used in the workshops offered during May and June. The project uses three files:
• TimeType.h, that contains the interface, or definition of the class;
• TimeType.cpp, that contains the implementation of the class; and
• TestTimeType.cpp, a program in which the class TimeType is used and tested.
Note that the header file for the class, TimeType.h is not added to the project. The implementation file for the
class, TimeType.cpp, however, must be added to the project.

How to create a Project: Step by Step for the TimeType class


Step 1(Optional): Create a folder for your project:
Double-click on My Computer on your desktop
Double-click (C:)
Click File → Click New → Click Folder
Name the folder: TimeType

Step 2: Starting Dev-C++


During installation, a shortcut to Dev-C++ should have been placed on the desktop. Double- click it
to start Dev-C++. Otherwise, you can click on the Windows "Start" button and choose "Bloodshed Dev-C++"
on the "Programs" submenu. Alternatively, you can navigate to the folder c:\unisa\devcpp and execute the
file devcpp.exe
Step 3: Creating a Project
Click File → Click New → Click Project
Click Console Application
Name the project: TimeType (indicated by A on Figure 1 below)
Click Ok

Figure 1
42

Navigate to the TimeType folder on your machine (indicated by B on Figure 2)

Figure 2

Click Save (Indicated by C on Figure 2 above)

Step 4: Editing a C++ source file


Type in the contents of TestTimeType.cpp (Indicated by D in Figure 3)

Figure 3

When you create a project as explained above, Dev-C++ automatically produces a source file
43 COS112V/101/3/2009

(Untitled1) from a template and opens it for you to edit. Note the Project Browser panel on
the left. You can click on the little plus sign next to the project icon to see what files have been
added to the project.
Click File →Click SaveAs... → save as TestTimeType.cpp

Step 5: Adding an implementation file to the project


Click File → Click New → Click Source File
Dialogue box appears with the message “Add new file to current Project?”
Click Yes
Type in the contents of TimeType.cpp
Click File →Click SaveAs... → save as TimeType.cpp

Step 6: Creating a header file


Click File → Click New →Click Source File
Dialogue box appears with the message “Add new file to current Project ?”
Click No
Type in the contents of TimeType.h
Click File→Click Save As... → save as TimeType.h

Step 7: Cross Check


Your screen should appear similar to Figure 4 below:
E + sign to see what files have been added to the project
F the two files that have been added to the project are listed
G header file TestTimeType.h
H client program TestTimeType.cpp - the only file that contains a main function
I implementation file, TimeType.cpp
Once your project has all these aspects in place, you can now compile your project (Step 8)
Step 8: Compiling and Running your Project
Click Execute → Compile & Run

Trouble Shooting
Error: [Linker error] undefined reference to `TimeType::TimeType()'
Problem: You have not done the implementation for this particular function or you have not added the
implementation file to the project

Special Precautions
Make sure you save your project as you work – Click File →Save All
If your project seems to be running the previous version then Click Execute →Rebuild All
44

H I

G
E
F

Figure 4

Discussion:
The reason why the interface and implementation of a class is often placed in separate files has to do with the idea of
encapsulation. The programmer who uses a class should only need to look at the interface to be able to use it
correctly in a program. For this reason, the interface is placed in a separate (header) file from the implementation.
Also, sometimes you don't want to distribute your source code, but you want other programmers to be able to use the
class(es) that you have defined. In this situation, you can simply provide the compiled (object) code of the
implementation together with the header file (which cannot be compiled separately). Note that when the interface
and implementation of a class is separated, we have to use the scope operator :: together with the name of the class
for the implementations of each of the separated functions.

Note, that we have created the client program (i.e. the program that uses the class) first
(TestTimeType.cpp), then the implementation file (TimeType.cpp) and then the header file
(TimeType.h) file. You may decide the order that best suits you, there is no specific order that is applicable.
Typically the header file is created first, as it is the blue print for the implementation file.
45 COS112V/101/3/2009

5. Using the debugger in Dev-C++


What is a debugger?
A debugger is a software utility that executes program code line by line while keeping track of the variables and the
functions in the program. This step-by-step execution allows you to detect errors in program code. By request, the
utility displays the contents of different variables during execution. The debugger also allows you to stop the
executing program at any point (using breakpoints) in the code, allowing you to examine data at the given point in
the program and also to verify the program code following that point.

Dev-C++ provides a debugger to provide the debugging facility. We will take a step-by-step approach to learn how
to use the debugger in Dev-C++. The Dev-C++ Help file also contains these instructions.

How to use the debugger with a program


There are two ways to use the debugger in Dev-C++.

Option 1: Once you have opened a project file, go to the"Tools | Compiler Options | Settings" tab, then select
"Linker" on the left hand side of the window, choose the "yes" option for the "Generate debugger
information" on the right hand side of the window and click on "OK"

Option 2: On the "Debug" menu select "Debug (F8)". If you do not have debugging information set in your
project as explained in step 1, Dev-C++ will prompt you with a "Confirm Window" asking if you
want to rebuild your program with debugging information enabled. Click on the "Yes" button. Your
project file will then rebuild to include the debugging information.

Now the debugger is ready to be used with the program.

The windows that display debug-related information


There are two windows used to display debug-related information:

1. The window under the "Debug" tab, to the left side of the IDE window (where your program is
displayed).

2. The window under the "Debug" tab, on the bottom section of the IDE window.

These windows will be used in the following sections.

How to use the debugger


Once the debugger has been enabled, you can run it by selecting "Debug" in the "Debug" menu or by selecting the
"Debug" button on the "Debug" tab at the bottom section of the IDE. Remember that you first need to compile a
program before the debugger can be used on the program.

Consider a simple program to calculate the area of two rectangles. We use this program to demonstrate various
aspects of debugging.
#include <iostream>
using namespace std;

int main() {
int length=10;
int width=5;
int area=length*width;

length=5;
width=2;
46

area=length*width;

return 0;
}

Adding breakpoints
Breakpoints are used to pause your program while debugging at a certain line of the program. The purpose of using a
breakpoint is to verify whether the specified line of code is executed and also to verify the variable values at that
point in the program.

To add a breakpoint:

1. First select the line of code where you want to break by simply positioning the text cursor on it. Now go to
the "Debug" menu and click on "Toggle Breakpoint"

OR

2. Click on the gutter (if it is visible on the left of the editor) next to the program line.

OR

3. Right-click on the line of code where you want to break and select "Toggle Breakpoint" on the displayed
menu.

When a breakpoint is added to a program line, the line will be highlighted in red. After choosing the breakpoint, you
can run the debugger. If the debugger has successfully reached the break-pointed line code, the colour of the
highlighted program line will change to blue. We set a breakpoint at line 6 in our example program. The two
screenshots below show this program line with the breakpoint added and the change in colour after the debugger is
run.

Screen shot 1

Screen shot 2

Screen shot 2 shows that execution has reached the break-pointed line of code. Now we can analyse the values of
different variables at the break-pointed line of code. Say for example, we want to verify the value of the variable
length at the break-pointed line of code. To do this, we add watch variables. We can add a watch variable in the
following ways:

1. Click on the "Watch" option of the "Debug" menu. Dev C++ will prompt you with a window named "New
Variable Watch" to enter the variable name that you want to put a watch on. For this example, we type the
variable name length

OR

2. Click on the "Add Watch" button on the "Debug" tab in the bottom section of the Dev-C++ window. The
same prompt to enter the variable name will appear.
47 COS112V/101/3/2009

OR

3. Right-click on the line of code where you want to break and then select "Add Watch" from the displayed
menu. The same prompt to enter the variable name will appear.

The variable name and the content of the variable will be displayed on the left hand side of the Dev C++ window on
the Debug window. The screen shot is given below.

Screen shot 3

In this way, we can add multiple watch variables to verify the contents of these variables. In such a simple program
the debugger may not appear to be particularly helpful, but for long and complex programs such a facility is very
useful.

The watch variables can be deleted by selecting these variables and by using the "Delete" button on the keyboard. To
deselect a breakpoint, go to the line of the program code that has the breakpoint and click on the breakpoint icon on
the gutter of the Editor, or select "Toggle Breakpoint" on an appropriate menu.

Stepping through the program


We can also use the debugger to step through a program to verify if the order of execution of the program is what we
intended. Once the program execution has reached the breakpoint, we can use three different ways of stepping
through the program. These are:

1. Choose "Next Step" on the "Debug" menu OR click on the "Next Step" button available on the "Debug"
tab at the bottom of the IDE window.
Function of "Next Step": The debugger will step one instruction (line of code) in your program.

2. Choose "Step Into" on the "Debug" menu OR click on the "Step Into" button available on the "Debug"
tab at the bottom of the IDE window.
Function of "Step Into": The debugger will step one instruction. If that instruction is a function call it
will step into the function.

3. Choose "Continue" on the "Debug" menu OR click on the "Continue" button available on the "Debug"
tab at the bottom of the IDE window.
Function of "Continue": The debugger will continue the execution of your program until another
breakpoint is reached.
These facilities are useful when debugging loops and functions. They help to verify the order of execution of the
program since each line of the program that is executed is marked blue and hence the lines that are not executed can
be easily detected.

Backtracing
This is used to display all the functions that were executed in a program before the debugger reached the break-
pointed line of code. The function names are displayed under the "Debug | Backtrace" tag on the bottom section of
the IDE window.
48

6. Printing
To print a C++ program, choose the "Print" option on the "File" menu of Dev-C++. If you are submitting an
assignment via myUnisa, simply paste the code of your program into a word processor file.

Printing the output of a program is somewhat trickier. There are (at least) two ways to print the output of a text-based
program (a console application):

Method 1
To print the text from the console window after running your program, you can copy the text to a word processor (an
editor). The steps involved are as follows:
1. Click on the Mark (first) button (after the Font drop-down list) on the toolbar of the console window.

2. Hold the Shift key down and use the arrow keys to mark (highlight) the text as a block.

3. Click on the Copy (second) button to copy the highlighted text to the clipboard.

4. You can now paste it in a word processor (editor) of your choice and print it.

Method 2
Sometimes the above method can be somewhat laborious and problematic, especially if there is so much output that it
scrolls off the top of the screen. In this case, you can send the output directly to the printer (while the program is
running) like this:
1. Open a DOS window (or Command window) and change the directory to where your program is. You will
need to type a DOS command for this, something like cd \unisa\cos112.

2. Check that you are in the correct directory by executing you program. For example, type first.exe and press
<Enter>. If the message "Bad command or filename" is displayed, you are either in the wrong directory or
the name of the executable file is incorrect. You must be able to run your program from the DOS prompt
before proceeding.

3. Make sure that your printer is switched on, is "On-line" and has paper in it, etc.

4. Press <Ctrl+P> to ensure that all the output generated from now on is sent to the printer.

5. Type the name of the executable file, eg. first.exe and press <Enter> to run your program again.

6. Enter any values that the program requires as input.

7. When the program terminates, press <Ctrl+P> again to turn off the printing mode. All the output (and input)
of the program should have been sent to the printer.

8. Now you can close the console window.

Unfortunately, this method won't help if you intend submitting your assignment via myUnisa. You'll have to use
Method 1.

7. Frequently Asked Questions


FAQ 01
The output of my C++ program just flashes on the screen, and then disappears. What can I do?
Answer
Go to the Environment options in the Tools Menu and select “Console Window Remains Open”. Also, ensure that
there are no spaces in the name of the folder/directory in which you store your program, in the program name itself or
in the project name.
49 COS112V/101/3/2009

FAQ 02
My C++ project won't compile, any suggestions?
Answer
Check that Dev-C++ knows where the MinGW compiler is. In particular, check the following in "Tools | Compiler
Options" under the "Directories" tab:
C:\unisa\mingw\bin should be added to "Binaries".
C:\unisa\mingw\lib should be added to "Libraries".
C:\unisa\mingw\include should be added to "C Includes".
"C++ Includes" should be empty
Note that if you installed the MinGW compiler in a directory other than the default (i.e. not in C:\unisa\mingw)
then you will have to change these paths accordingly.

FAQ 03
I get an error “unable to run program file”. What is wrong?
Answer
Check that the filename for the “make:” option in the “Programs” tab under “Tools|Compiler Options” is
mingw32-make.exe. This will usually solve this error.

FAQ 04
Why do I keep getting weird error messages about “path not found” when I try to compile a program?
Answer
After checking all the paths as discussed in FAQs 03 and 04 you can try replacing the contents of
AUTOEXEC.NT (in the system32 folder in Windows XP) with the following:
@echo off
REM AUTOEXEC.BAT is not used to initialize the MS-DOS environment.
REM AUTOEXEC.NT is used to initialize the MS-DOS environment unless a
REM different startup file is specified in an application's PIF.
REM Install CD ROM extensions
lh %SystemRoot%\system32\mscdexnt.exe
REM Install network redirector (load before dosx.exe)
lh %SystemRoot%\system32\redir
REM Install DPMI support
lh %SystemRoot%\system32\dosx
Replace the contents of CONFIG.NT (in the system32 folder in Windows XP) with the following:
REM Windows MS-DOS Startup File
REM
REM CONFIG.SYS vs CONFIG.NT
REM CONFIG.SYS is not used to initialize the MS-DOS environment.
REM CONFIG.NT is used to initialize the MS-DOS environment unless a
REM different startup file is specified in an application's PIF.
REM
dos=high, umb
device=%SystemRoot%\system32\himem.sys
files=40

FAQ 05
I get an error message that says "Undefined reference to _monstartup". What can I do?
Answer
Go to "Project | Project Options | Compiler"
For the "Default compiler" click on "Code profiling" and make sure it is set to "No".
Also check the setting under "Tools | Compiler Options | Settings" for "Code profiling" and make sure it is set to
"No".
50

FAQ 06
I accidently choose the wrong language during setup and the Dev-C++ IDE appeared in another language. How
do I change the language back to English?
Answer
Uninstall Dev-C++, and then search for the hidden devcpp.ini files (there should be 2), delete them and install
Dev-C++ again. This is the easiest way to reset the initial settings.

8. CodeMate
The prescribed book (Walter Savitch. Problem Solving with C++, 6th edition. Pearson International Edition:
Addison-Wesley, 2006, ISBN 0-321-44263-6) comes wrapped with a CodeMate Student Access Kit. Codemate
is part of an online resource centre and interactive teaching tool maintained by the Addison-Wesley Publishers.
CodeMate allows you to practice using the code examples and end-of-chapter problems from the book. It also
offers an electronic version of the textbook, chapter quizzes on programming concepts, PowerPoint slides and
source code.

Although some of the questions set for the assignments do have CodeMate support, the COS112-V lecturers do
not expect you to use CodeMate to do the assignment questions, and consequently we do not support
CodeMate. However, if you do wish to use CodeMate take note of the following:
• In order to use CodeMate, you need an online connection, and you have to register online by following the
instructions given in the CodeMate Student Access Kit. Note that you registration will only be valid for six
months. You can purchase further access codes online, or, alternatively only register for CodeMate in
May/April so that your registration is valid until October.
• One of the certificate courses offered by CENSE, use CodeMate to submit their assignments. Please do not
register for this course! Use CodeMate on your own.
• You also require the Java Runtime Environment JRE 1.4 or newer to use CodeMate. JRE 1.4.2_05 can be
found on Disk 2008. To install JRE 1.4.2_05, navigate to \install\java on the CD, double-click on
JavaSetup.exe and follow the instructions from there.
• Both cookies and popups have to be enabled for both codemate.aw-bc.com and codemate.pearsoncmg.com.
If you use Microsoft Internet Explorer, click on Tools => Internet Options => Privacy. From there you can
navigate to the required cookies and popups. To check if your system configuration meets the CodeMate
requirements, log in after registering, go to MyCodeMate Exercises and click on Online Systems
Requirements Check. You may find it useful to click on Take a tour on the registration page before
registering, and to work through the demo available on the CodeMate homepage.
• You need fast Internet access to develop and test programs with the CodeMate compiler. If you have a dialup
link, this is not feasible. In this case, download the program shell provided by CodeMate for each exercise.
Then use the compiler and IDE provided on Disk 2008 to develop your program.
• A feasible option is to download the end-of-chapter quizzes, do it offline, log on again to complete the bullets and
then submit it online to be marked.
51 COS112V/101/3/2009

Appendix B: How to install the software on Vista:


1. Install mingw and devcpp as instructed on DISK 2008 (also in Tutorial Letter 104 for COS111U or
Tutorial Letter 102 for COS112V).
2. Run the compatibility wizard by doing the following:
2.1 Click on Start
2.2 Choose Control Panel
2.3 Type ‘compatibility’ in the Search block (top right of Control Panel window)
2.4 Click on ‘Use an older program with this version of Windows’ under Default Programs as
shown below:

2.5 The Program Compatibility Wizard window will appear. Click on Next.
2.6 In the following window, choose ‘I want to locate the program manually’ and click on Next.
2.7 In the window that appears (see below) either browse to find devcpp or type the following path:
C:\unisa\devcpp\devcpp.exe. Then click on Next.
52

2.8 Choose Microsoft Windows XP (Service Pack 2) in the window that follows and click on Next:
2.9 Leave the display settings as is in the following window, and click on Next:
2.10 Click the checkbox to run the program as an administrator in the following window and click on
Next. NB Devcpp must be run as an administrator!
2.11 Click on Next to check the compatibility settings in the following window.
2.12 This will take you to Devcpp where you can set the initial settings (i.e choose the language and
set up the cache). Once that is done, close Devcpp and return to the following window :

2.13 Click on Next


2.14 Choose No in the following window and then click on Next
2.15 Click Finish in the next window to complete the Program Compatibility Wizard.
3. Now you need to create a shortcut to Devcpp. To set up the shortcut to DevCpp follow the steps below:
3.1 Click on Start
3.2 Choose Computer
3.3 Double-click on C:
3.4 Double-click on unisa
3.5 Double-click on devcpp
3.6 Select devcpp application as shown in the window below

3.7 Right-click on devcpp application, choose Send To in the pop-up menu and then Desktop
53 COS112V/101/3/2009

(Create shortcut) as shown below.

This will place the following shortcut on the desktop:

3.8 Double-click on the shortcut to activate devcpp.


54

Appendix C: Source listings of the sample programs in


the textbook
The source listings of the sample programs in the text book can be found at http://www.aw.com/cssupport.
Click on S under “Author Search”, and then on “Savitch” in the resulting list of authors. Follow the link
provided for the text book. Now double-click on “PSCPP6e-SourceCode.zip” and click on Open. A list of
folders, one for each chapter, will be displayed. Each folder contains the source listings for Displays in the
chapter. Display 9.06 for example will be listed as “09-06.cpp”. If you double-click on the file, the source listing
will open up in DevC++.
55 COS112V/101/3/2009

Appendix D: Solution to assignment 3


Question 1
Discussion:
In this program we use C-strings to read in the user's first and last name. Both C-strings are then converted to
lowercase before the full name is converted to pig latin.

C-strings use the '\0' character to indicate the end of a C-string. The C-string variables used to store the first and
last names for example are therefore declared as
char first[21], last[21];
to allow 20 characters each for the first and last names as well as one position for the '\0'.

The program uses two functions, convertToLowerCase() to convert a string to lowercase, and
pigLatin() to convert a string to pig latin.

In function convertToLowerCase() we use the null character '\0' as sentinel in the while loop that
converts each character to its lower case.

Program listing:
#include <iostream>
#include <cstring>
using namespace std;

// void convertToLowerCase(char name[])


// Pre: name[] contains a C-string
// Post: name[] has been converted to lower case
void convertToLowerCase(char name[])

//void pigLatin(char name[])


// Pre: name[] contains a C-string
// Post: name[] has been converted to pig latin
void pigLatin(char name[])

int main()
{
char first[21], last[21], newName[41], copyFirst[21], copyLast[21];
cout << "Please enter your first name: ";
cin >> first;
cout << "Please enter your last name: ";
cin >> last;
//make a copy of the first and last name for output purposes
strcpy(copyFirst, first);
strcpy(copyLast, last);
//convert first and last name to lowercase
convertToLowerCase(first);
convertToLowerCase(last);
//convert first and last name to pig latin
pigLatin(first);
pigLatin(last);
//create new string with first and last name in pig latin
strcpy(newName, first);
strcat(newName, " "); //add space between first and last name
strcat(newName, last);
cout << "Dear " << copyFirst << " " << copyLast
<< " in pig latin your name is " << newName << endl;
56

return 0;
}

void convertToLowerCase(char name[])


{
int i = 0;
while (name[i] != '\0')
{
name[i] = tolower(name[i]);
i++;
}
}

void pigLatin(char name[])


{
char ch;
if ((name[0] == 'a') || (name[0] == 'e') || (name[0] == 'i')
|| (name[0] == '0') || (name[0] == 'u'))
{
name[0] = toupper(name[0]);
strcat(name, "way");
}
else
{
ch = name[0];
for (int i = 0; i <= strlen(name); i++)
name[i] = name[i+1];
name[strlen(name)] = ch;
strcat(name, "ay");
name[0] = toupper(name[0]);
}
}

Input and corresponding output:


Please enter your first name: Erin
Please enter your last name: Jones
Dear Erin Jones in pig latin your name is Erinway Onesjay
Press any key to continue . . .

Question 2
2. (a) Discussion:
We adapted the sorting function to sort a vector from largest to smallest as follows:
The argument was changed from an array of ints to a vector of ints, as can be seen in the function
headings:
void sort(vector<int>& v) and
int index_of_largest(const vector<int> v, int start_index)

Note that in order to return the sorted vector, it should be a reference parameter. Also note that since the size of a
vector can be determined with the member function size(), the parameter number_used can be omitted
from both functions.

We want to sort in descending order while the sorting function in Display 7.12 sorts in ascending order.
Accordingly, both function and local variable names that refer to either 'smallest' or 'min' have been
changed to 'largest' or 'max'. See for example function index_of_largest below:
int index_of_largest(const vector<int> v, int start_index)
{
57 COS112V/101/3/2009

int max = v[start_index],


index_of_max = start_index;
for (int index = start_index + 1; index < v.size(); index++)
if (v[index] > max)
{
max = v[index];
index_of_max = index;
//max is the largest of v[start_index] through v[index]
}

return index_of_max;
}

While these name changes aid in understanding the sorting order of the sorting function, it does not change the
order in which the vector is sorted from ascending to descending. The crucial change to ensure that the sorting is
done in descending order instead of ascending order, lies in changing the comparison
if (a[index] < min)
in function index_of_largest to
if (v[index] > max)
This change is highlighted in the code section above. The comments have also been adapted to reflect the
changed sorting order.

2. (b) Discussion:

In this question you should have provided a facility to allow the user to specify whether input should be read
from a file, or from the keyboard. Note that when input is read from the keyboard, we indicate the end of file
character with CTRL Z, followed by pressing 'enter':
{ //read input from the console
cout << "Please enter list of values. Press 'enter' "
<< "after each value. Use CTRL Z to end." << endl;
read_vector(list,cin);
}

In function read_vector() inheritance is used so that input can be done both from a file or from the keyboard.
The formal parameter corresponding either to cin (console input) or fin (file input) therefore has to be of type
istream:
void read_vector(vector<int>& v, istream& in_stream);
See Section 10.4 on p 614 in Savitch for more detail.

The distinct elements in the vector are extracted by using a boolean function found() to determine whether or
not a specific element in the original vector (list) occurs in the vector of distinct elements (distinct).
Should a specific element not occur in the vector of distinct elements, it is added to distinct.
//extract distinct elements in list into vector distinct
vector<int> distinct;
for (unsigned int i = 0; i < list.size(); i++)
{
if (!found(list[i], distinct))
distinct.push_back(list[i]);
}

The vector of distinct elements is then sorted, and a third vector (occurrences) with the same number of
elements as distinct is declared and initialised to 0.
//sort vector distinct
sort(distinct);

//declare a vector with distinct.size()elements and initialise


//each to 0
58

vector<int> occurrences (distinct.size());

A function count() is used to count the number of times each distinct element (stored in vector distinct),
occurs in the original list of elements (vector list).
//count occurrences for each element in vector distinct
for (unsigned int i = 0; i < distinct.size(); i++)
occurrences[i] = count(distinct[i], list);

Finally, the corresponding elements in vectors distinct and occurrences are output next to each other to
show the number of times each distinct element occurs in the original list. We show output for input from the
keyboard as well as for input from a file.

Program listing:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>

using namespace std;

void read_vector(vector<int>& v, istream& in_stream);


//to read input values from a stream (file or console) into vector v
bool found(int x, vector<int> v);
//to determine if x occurs in vector v

int count(int x, vector<int> v);


//to count the number of times x occurs in vector v

void sort(vector<int>& v);


//Precondition: number_used <= declared size of the vector v.
//The vector elements v[0] through v[v.size - 1] have values.
//Postcondition: The values of v[0] through v[v.size() - 1] have
//been rearranged so that v[0] >= v[1] >= ... >= v[v.size() - 1].

void swap_values(int& v1, int& v2);


//Interchanges the values of v1 and v2.

int index_of_largest(const vector<int> v, int start_index);


//Precondition: 0 <= start_index < v.size(). Referenced vector elements
//have values.
//Returns the index i such that v[i] is the largest of the values
//v[start_index], v[start_index + 1], ..., v[v.size() - 1].

int main()
{
vector<int> list;
fstream fin;
char answer;
string filename;
int next;
cout << "Do you want to provide input via console or "
<< "using a file(c/f)?";
cin >> answer;
cout << endl;
if (answer == 'f') //read input from a file
{
59 COS112V/101/3/2009

cout << "Please enter filename: " << endl;


cin >> filename;
fin.open(filename.c_str());
if (fin.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}
read_vector(list,fin);
fin.close();
}
else //read input from the console
{
cout << "Please enter list of values. Press 'enter' "
<< "after each value. Use CTRL Z to end." << endl;
read_vector(list,cin);
}

//extract distinct elements in list into vector distinct


vector<int> distinct;
for (unsigned int i = 0; i < list.size(); i++)
{
if (!found(list[i], distinct))
distinct.push_back(list[i]);
}
//sort vector distinct
sort(distinct);

//declare a vector with distinct.size()elements and initialise


//each to 0
vector<int> occurrences (distinct.size());

//count occurrences for each element in vector distinct


for (unsigned int i = 0; i < distinct.size(); i++)
occurrences[i] = count(distinct[i], list);

//output
cout << endl << 'N' << '\t' << "Count" << endl;
for (unsigned int i = 0; i < distinct.size(); i++)
cout << distinct[i] << '\t' << occurrences[i] << endl;

return 0;
}

void read_vector(vector<int>& v, istream& in_stream)


{
int next;
while (in_stream >> next)
{
v.push_back(next);
}
}

bool found(int x, vector<int> v)


{
for (unsigned int i = 0; i < v.size(); i++)
{
if (x == v[i])
return true;
}
60

return false;
}

int count(int x, vector<int> v)


{
int counter = 0;
for (unsigned int i = 0; i < v.size(); i++)
{
if (x == v[i])
counter += 1;
}
return counter;
}

void sort(vector<int>& v)
{
int index_of_next_largest;

for (unsigned int index = 0; index < v.size() - 1; index++)


{//Place the correct value in v[index]:
index_of_next_largest =
index_of_largest(v, index);
swap_values(v[index], v[index_of_next_largest]);
//v[0] >= v[1] >=...>= v[index] are the largest of the original
//vector elements. The rest of the elements are in the remaining
//positions.
}
}

void swap_values(int& v1, int& v2)


{
int temp;
temp = v1;
v1 = v2;
v2 = temp;
}

int index_of_largest(const vector<int> v, int start_index)


{
int max = v[start_index],
index_of_max = start_index;
for (int index = start_index + 1; index < v.size(); index++)
if (v[index] > max)
{
max = v[index];
index_of_max = index;
//max is the largest of v[start_index] through v[index]
}

return index_of_max;
}

Output using console input:


Do you want to provide input via console or using a file(c/f)?c

Please enter list of values. Press 'enter' after each value. Use CTRL Z to
end.
-12
3
-12
61 COS112V/101/3/2009

4
1
1
-12
1
-1
1
2
3
4
2
3
-12
^Z

N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
Press any key to continue . . .

Output using file input:


Do you want to provide input via console or using a file(c/f)?f

Please enter filename:


Q6.dat

N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
Press any key to continue . . .

Question 3
For this question you had to write a recursive function that returns the sum of the integers between any two
integer numbers inclusive. This recursive function expects two integer parameters and returns a double.

Program Listing:
#include <iostream>
using namespace std;

double sum (int m, int n)


{
if (m == n)
return m;
else
return (m + sum ( m + 1, n ) );
}

int main() {
cout << "The sum between 13 and 17 is:";
cout << sum (13,17) <<endl;;
62

cout << "The sum between 13 and 13 is:";


cout<< sum(13,13) <<endl;
cout << "The sum between 13 and 14 is:";
cout<< sum(13,14) <<endl;

return 0;
}

Output:
The sum between 13 and 17 is:75
The sum between 13 and 13 is:13
The sum between 13 and 14 is:27
Press any key to continue . . .

Discussion:

To solve this question, we need to determine the base case and the general case. The base case is when the
solution can be obtained directly.

The base case:


If m is equal to n then we can immediately determine the sum to be m. For example the sum between 13 and 13
would be 13.

The general case on the other hand, is a little harder to deduce:


Consider the following example:
sum(13,17) = 13 + 14 + 15 + 16 + 17

A more general formula can be written as:


sum(m,n) = m+(m+1)+(m+2)+...+(n-2)+(n-1)+n

Recursively:
sum(m,n) = m + sum(m+1,n)
63 COS112V/101/3/2009

The diagram below represents the recursive calls that will take place if 13 and 17 were passed as parameters to
the sum() function. That is, we want to determine the sum between 13 and 17. The diagram shows that each
sum(m,n) induces calls to sum(m+1,n). For instance, since sum(13,17) = 13 + sum(14,17) - this
induces calls to sum(15,17), sum(16,17) and finally sum(17,17). With regard to the diagram below,
recursion works first along the downward arrows until a given point is reached at which an answer is defined
(the base case), and then works along the dashed upward arrows, returning values back to the calling function.
For function sum(), the base case is when m == n.

sum(13,17) sum(13,17) = 75

since m!=n
return 13 + sum (14,17); return 13 + 62 = 75
step a

sum(14,17) = 62
sum(14,17)

since m!=n return 14 + 48 = 62


return 14 + sum (15,17);
step b

sum(15,17) = 48
sum(15,17)

since m != n return 15 + 33 = 48
return 15 + sum(16,17)
step c

sum(16,17) = 33
sum(16,17)

since m != n return16 +17 = 33


return 16 + sum(17,17)
step d
sum(17,17) = 17

sum(17,17)

since m = n return 17
return 17
step e

So eventually the recursive calls will stop at sum (17,17) - because an answer of 17 can be returned.

Hence sum(16,17) is:


sum(16,17) = 16 + 17 = 33 hence sum(16,17) returns 33

So sum(15,17) is:
sum(15,17) = 15 + sum(16,17) = 15 + 33 = 48 hence sum(15,17) returns 48

So sum(14,17) is:
sum(14,17) = 14 + Sum(15,17) = 14 + 48 = 62 hence sum(14,17) returns 62

Therefore sum(13,17) is:


sum(13,17) = 13 + sum(14,17) = 13 + 62 = 75 hence sum(13,17) returns 75
64

More on Recursion:
Understanding recursion is difficult. Let us consider an everyday example. Suppose you were given a huge bag
of coins and you had to determine how much money was in the bag.
As the bag is large, you prefer not to do the work by yourself. However, you have many willing
friends. You divide the bag of coins into two heaps of coins and ask your friend "Could you
please add up this one heap of coins? I've only given you half, so there's half the work to do”.
You, then give the other half to another friend, and say the same thing. Once both are done, they
will give their answer to you, and you add their results.
Thus, you have broken down the problem into two smaller parts, and asked your friends to do the work.
Now those friends are smart too, so they divide their heap of coins into two parts (now each has two heaps of ¼
of the size) and each asks two of their friends to help. When their friends are done, they return their answer, and
the result is summed. Now assume that each of their friends does the same and enlists more friends to help and
this process goes on and on. Eventually, there is a heap of only two coins, and these are divided once again and
given to two more friends, and those friends, seeing how silly the problem is now, just tell the first friend the
only value on the coin. There's no need to ask any more friends, because you're down to one coin (this is the base
case).
Thus, recursion is all about breaking a problem down, and solving that, and that smaller problem is solved by
breaking it down some more, and trying to solve that. Eventually, you reach an easy solution (the base case), and
return the solution.

Question 4
For this question you had to answer questions based on the following code fragment:

1: #include <iostream>
2: using namespace std;
3:
4: //------------------------------------------
5:
6: class A
7: {
8: private:
9: int x;
10: protected:
11: int getX();
12: public:
13: void setX();
14: };
15:
16: int A::getX()
17: {
18: return x;
19: }
20:
21: void A::setX()
22: {
23: x=10;
24: }
25:
26: //----------------------------------------------
27: class B
28: {
29: private:
30: int y;
31: protected:
32: A objA;
33: int getY();
65 COS112V/101/3/2009

34: public:
35: void setY();
37: };
38:
39: void B::setY()
40: {
41: y=24;
42: int a=objA.getX();
43: }
44:
45: //----------------------------------------------
46:
47: class C: public A
48: {
49: protected:
50: int z;
51: public:
52: int getZ();
53: void setZ();
54: };
55:
56: int C::getZ()
57: {
58: return z;
59: }
60:
61: void C::setZ()
62: {
63: z=65;
64: }

Answer the following questions based on the code fragment given above:

(a) Is line 18 a valid access? Justify your answer?


Yes.
The variable x is a private data member of the class A and therefore it can only be accessed by other
member functions and operators of the class A. getX() is a member function of class A and therefore
line 18 is a valid access.

(b) Is line 32 a valid statement? Justify your answer.


Yes.
An object of class A has been included as a protected data member of class B.

(c) Identify another invalid access statement in the code.


Line 42 (int a=objA.getX();) is invalid.
getx() is a protected member function of class A and can therefore only be accessed by other
member functions and operators of the class A and by classes derived from class A.

Class C has public inheritance with the class A. Identify and list class C’s private, protected and
public data members resulting from the inheritance.
With public inheritance, the public and protected members of the base class A are inherited as public
and protected members of the derived class C.
Private data members or member functions resulting from the inheritance: None
Protected data members or member functions resulting from the inheritance: getX()
Public data members or member functions resulting from the inheritance: setX()

If class C had protected inheritance with the class A, identify and list class C’s private, protected and
66

public data members resulting from the inheritance.


With protected inheritance, public and protected members of the base class become protected
members of the derived class.
Private data members or member functions resulting from the inheritance: None
Protected data members or member functions resulting from the inheritance: setX() and getX()
Public data members or member functions resulting from the inheritance: None

Discussion:
When deriving a class from a public base class, public members of the base class become public
members of the derived class and protected members of the base class become protected members of the
derived class. A base class’ private members are never directly accessible from a derived class, but can be
accessed through calls to the public and protected members of the base class.

When deriving from a protected base class, public and protected members of the base class become
protected members of the derived class. When deriving from a private base class, public and
protected members of the base class become private members of the derived class. Private and
protected inheritance are not “is-a” relationships [Reference: Tutorial Letter 501, chapter 15].

Question 5
For this question you had to answer questions based on the following code fragment:

class Date{
public:
friend ostream & operator<<(ostream & cout, const Date & d);
Date(int y, int m, int d);
private:
int year, month, day;
};

class Publication {
public:
Publication(const string & p, const Date & d,
const string & t);
Date GetDate( ) const;
string GetPublisher( )const;
string GetTitle() const;
private:
string publisher;
Date date;
string title;
};

(a) Implement the Date and the Publication classes.

File Name: Date.cpp


#include <iostream>
#include "Date.h"

using namespace std;

Date::Date(int y, int m, int d): year(y), month(m), day(d){}


ostream & operator<<(ostream & out, const Date & d){
out<<d.day<<"/"<<d.month<<"/"<<d.year<<endl;
}
67 COS112V/101/3/2009

File Name: Publication.cpp


#include <iostream>
#include <string>
#include "Date.h"
#include "Publication.h"

using namespace std;

Publication::Publication( const string & p, const Date & d,


const string & t): publisher(p),date(d),title(t)
{ }

Date Publication::GetDate() const


{
return date;
}

string Publication::GetPublisher()const
{
return publisher;
}

string Publication::GetTitle() const


{
return title;
}

(b) Code the interface of a derived class Book for which the Publication class is the base class. The
Book class has two additional data members representing the ISBN number and the author of a book.
Furthermore, the Book class contains member functions getISBN( ) and getAuthor( ) that returns
the ISBN number and the author respectively. The declaration must also include a constructor for the class
Book.

#ifndef BOOK_H
#define BOOK_H
#include "Publication.h"
#include "Date.h"
#include <string>

using namespace std;

class Book: public Publication{


public:
Book(const string & p, const Date & d, const string & t, const
string & auth, const string & isbn);
string getAuthor()const;
string getISBN()const;
private:
string ISBN;
string author;

};

#endif

(c) Implement the Book class.

#include "Book.h"
68

#include <string>
using namespace std;
Book::Book(const string & p, const Date & d, const string & t, const
string & auth, const string & isbn):
Publication(p,d,t),
ISBN(isbn), author(auth){}

string Book::getAuthor()const{
return author;
}

string Book::getISBN() const {


return ISBN;
}

Note, the constructors of the Book class call the Publication constructor (shown in bold) in their initializer
lists. Constructing a derived class object by first constructing its inherited portion is a standard practice. (For a
complete discussion on this subject - refer to pages 865-868 of Savitch, under the section entitled "Constructors
in Derived Classes").

(d) Recode the following interface such that class Magazine, derives from class Publication:
#ifndef MAGAZINE_H
#define MAGAZINE_H
#include "Publication.h"
class Magazine: public Publication {
public:
Magazine(const string & p, const Date & d, const string & t, int ipy);
int GetIssuesPerYear( ) const;

private:
int issuesPerYear;
};
#endif

Note how the class requires less code due to inheritance.

(e) Implement the Magazine class.


#include "Magazine.h"

Magazine::Magazine(const string & p, const Date & d, const string & t, int
ipy):Publication(p,d,t), issuesPerYear(ipy)
{}

int Magazine::GetIssuesPerYear()const{
return issuesPerYear;
}

(f) For this question you had to design a driver program to test your classes:

#include <iostream>
#include "Date.h"
#include "Publication.h"
#include "Book.h"
#include "Magazine.h"

using namespace std;


int main(){
Date date1(2000,1,1);
Date date2(2005,2,2);
69 COS112V/101/3/2009

Book B("FisherKing", date1, "Global Warming", "123456789",


"Ann Miller");
cout<<B.GetTitle()<<endl;
cout<<B.GetPublisher()<<endl;
cout<<B.GetDate()<<endl;
cout<<B.getAuthor()<<endl;
cout<<B.getISBN()<<endl;
Magazine M("Blue Marlin", date2, "TheEarth and the Environment",12);
cout<<M.GetTitle()<<endl;
cout<<M.GetPublisher()<<endl;
cout<<M.GetDate()<<endl;
cout<<M.GetIssuesPerYear()<<endl;

return 0;
}

(h) Write a statement to overload operator<< as a friend function to the class Book and insert the following
implementation to your code:

ostream & operator<<(ostream & out, const Book & B){


out<<B.title<<endl;
out<<B.publisher<<endl;
out<<B.date<<endl;
out<<B.author<<endl;
out<<B.ISBN<<endl;
}

You should obtain the following compiler errors:

In function `std::ostream& operator<<(std::ostream&, const Book&)':


error: `std::string Publication::title' is private
error: `std::string Publication::publisher' is private
error: `Date Publication::date' is private

Suggest two ways to fix this compiler problem.

Method 1: Use the accessor functions as shown below:


ostream & operator<<(ostream & out, const Book & B){
out<<B.GetTitle()<<endl;
out<<B.GetPublisher()<<endl;
out<<B.GetDate()<<endl;
out<<B.getAuthor()<<endl;
out<<B.getISBN()<<endl;
}

Method 2: Change the member variables of Publication into protected access. As they are now
protected and not private they become accessible to the derived class Book. The protected members of
Publication become protected members of Book. They now can be directly accessed by member functions
and friend functions of Book.

class Publication {
public:
Publication(const string & p, const Date & d, const string & t);
Date GetDate( ) const;
string GetPublisher( )const;
string GetTitle() const;
protected:
70

string publisher;
Date date;
string title;
};

Full Programming Listing:


File name: Date.h
#ifndef DATE_H
#define DATE_H
#include <iostream>

using namespace std;


class Date{
public:
friend ostream & operator<<(ostream & cout, const Date & d);
Date(int y, int m, int d);
private:
int year, month, day;
};

#endif

File name: Date.cpp


#include <iostream>
#include "Date.h"

using namespace std;

Date::Date(int y, int m, int d): year(y), month(m), day(d){}


ostream & operator<<(ostream & out, const Date & d){
out<<d.day<<"/"<<d.month<<"/"<<d.year<<endl;
}

File name: Publication.h


#ifndef PUBLICATION_H
#define PUBLICATION_H
#include <string>
#include "Date.h"

using namespace std;


class Publication {
public:
Publication(const string & p, const Date & d, const string & t);
Date GetDate( ) const;
string GetPublisher( )const;
string GetTitle() const;
private:
string publisher;
Date date;
string title;
};

#endif

File name:Publication.cpp
#include <iostream>
#include <string>
#include "Date.h"
#include "Publication.h"
71 COS112V/101/3/2009

using namespace std;

string Publication::GetTitle() const{


return title;
}
Publication::Publication( const string & p, const Date & d, const string &
t): publisher(p),date(d),title(t){}

Date Publication::GetDate() const{


return date;
}

string Publication::GetPublisher()const{
return publisher;
}

Filename: Book.h
#ifndef BOOK_H
#define BOOK_H
#include "Publication.h"
#include "Date.h"
#include <string>

using namespace std;

class Book: public Publication{


public:
friend ostream & operator << (ostream & out, const Book & B);
Book(const string & p, const Date & d, const string & t, const string &
auth,const string & isbn);
string getAuthor()const;
string getISBN()const;
private:
string ISBN;
string author;
};

#endif

Filename: Book.cpp
#include "Book.h"
#include <string>
using namespace std;

Book::Book(const string & p, const Date & d, const string & t, const
string & auth, const string & isbn):
Publication(p,d,t),
ISBN(isbn), author(auth){}

string Book::getAuthor()const{
return author;
}

string Book::getISBN() const{


return ISBN;
}
ostream & operator<<(ostream & out, const Book & B){
out<<B.GetTitle()<<endl;
out<<B.GetPublisher()<<endl;
out<<B.GetDate()<<endl;
72

out<<B.getAuthor()<<endl;
out<<B.getISBN()<<endl;
}

Filename: Magazine.h
#ifndef MAGAZINE_H
#define MAGAZINE_H

#include "Publication.h"
class Magazine:public Publication {
public:
Magazine(const string & p, const Date & d, const string & t, int
ipy);
int GetIssuesPerYear( ) const;
private:
int issuesPerYear;
};
#endif

Filename: Magazine.cpp
#include "Magazine.h"

Magazine::Magazine(const string & p, const Date & d, const string & t, int
ipy):Publication(p,d,t), issuesPerYear(ipy)
{}

int Magazine::GetIssuesPerYear()const
{
return issuesPerYear;
}

Filename: Test.cpp
#include <iostream>
#include "Date.h"
#include "Publication.h"
#include "Book.h"
#include "Magazine.h"

using namespace std;


int main(){
Date date1(2000,1,1);
Date date2(2005,2,2);

Book B("FisherKing", date1, "Global Warming", "123456789",


"Ann Miller");
cout<<B.GetTitle()<<endl;
cout<<B.GetPublisher()<<endl;
cout<<B.GetDate()<<endl;
cout<<B.getAuthor()<<endl;
cout<<B.getISBN()<<endl;
Magazine M("Blue Marlin", date2, "TheEarth and the Environment",12);
cout<<M.GetTitle()<<endl;
cout<<M.GetPublisher()<<endl;
cout<<M.GetDate()<<endl;
cout<<M.GetIssuesPerYear()<<endl;

return 0;
}
73 COS112V/101/3/2009

Question 6
Discussion:
For this question, you had to define a function template that searches an array for a specific value and returns the
index of the first occurrence of that value. The template should have parameters for a partially filled array and
for a value of the base type of the array. If the value is in the partially filled array, then the function returns the
index of the first occurrence of that value, otherwise the function returns -1. The base type of the array is a type
parameter.

Function templates are special functions that can operate with generic types. This allows us to create a function
template whose functionality can be adapted to more than one variable type or class without repeating the code
for each type. For instance, with this program we used the same search() function for an array of doubles (
Doubles), an array of characters (Characters) and an array of integers (Integers). Without templates
we would have had to write a separate search() function for each type of array. (Section 17.1 of Savitch has
detailed explanations on the declarations of function templates.)

A template parameter is a special kind of parameter that can be used to pass a type as a parameter. The function
templates can use these parameters as if they were regular types. The declaration for the search() function
combined template parameters with a defined parameter type:
template<class T>
int search( T array[], int n, T target)

Be cautious when using template parameters - you cannot apply it without considering all the implications.
For example:
template<class T>
int search( T array[], T n, T target)
* This does not make sense as we want to run a loop n number of times to search the array for our target
element - n must certainly be of type integer. Hence it does not make sense within this context to declare n as a
template parameter.

Program Listing:
#include <iostream>

//Precondition: the array base type must have operator== defined,


//&& n <= declared size of the array argument.
//Postcondition: Function returns index of the first
//occurrence of target in array. If target is not in the
//array, the function returns -1

using namespace std;

template<class T>
int search( T array[], int n, T target)
{
for ( int i = 0; i < n; i++ )
{
if (array[i] == target)
return i;
}
return -1;
}

int main(){
char Characters[14] = { 'M', 'A', 'P', 'C','E' };
int Integers[14] = { 1, 4, 3, 5, 3, 6, 8, 9, 10, 7};
double Doubles[14] = {2.99,8.77,4.88,6.44,3.45};
74

cout << " C found at index "


<< search( Characters,5,'C')
<< " in array of characters"
<< endl;
cout << " c found at index "
<< search( Characters,5,'c')
<< " in array of characters"
<< endl;
cout << " 5 found at index "
<< search( Integers, 10, 5)
<< " in array of integers"
<< endl;
cout << " 3.45 found at index "
<< search( Doubles, 10, 3.45)
<< " in array of doubles"
<< endl;
}

Output:
C found at index 3 in array of characters
c found at index -1 in array of characters
5 found at index 3 in array of integers
3.45 found at index 4 in array of doubles
Press any key to continue . . .

Question 7
Discussion:
For this question, you had to specify a template version of a search function to determine whether an array
contains a particular value. Here only two of the parameters had to be template type parameters, namely the array
type and the target (i.e. the element being searched). As discussed, with the previous question, it does not make
sense to alter the other parameters into template type parameters. We also included a templatized Output()
function to output an array of any type and to call the search() algorithm to further promote reuse.

Program Listing:
#include <iostream>
#include <string>
using namespace std;

//Precondition: the array base type must have operator== defined,


//&& n <= declared size of the array argument.
//Postcondition: Function returns true at the first
//occurrence of target in array. If target is not in the
//array, the function returns false

template<class T>
bool search( T array[], int n, T target)
{
for ( int i = 0; i < n; i++ ){
if (array[i] == target)
return true;
}
return false;
}
//Precondition: the array base type must have operator<< defined,
//&& n <= declared size of the array argument.
75 COS112V/101/3/2009

template <class T>


void Output(T array[], int n, T target, string s){
if (search(array,n,target))
cout << s << "does contain " << target <<endl;
else
cout << s << "does not contain " << target <<endl;
}

int main(){
char Characters[14] = { 'M', 'A', 'P', 'C','E' };
int Integers[14] = { 1, 4, 3, 5, 3, 6, 8, 9, 10, 7};
double Doubles[14] = {2.99,8.77,4.88,6.44,3.45};

Output( Characters,5,'C', "Array Characters ");


Output( Characters,5,'c', "Array Characters ");
Output( Integers, 10, 5 , "Array Integers ");
Output( Integers, 10, 15 , "Array Integers ");
Output( Doubles, 10, 3.45, "Array Doubles ");
Output( Doubles, 10, 3.455, "Array Doubles ");
}

Output:
Array Characters does contain C
Array Characters does not contain c
Array Integers does contain 5
Array Integers does not contain 15
Array Doubles does contain 3.45
Array Doubles does not contain 3.455
Press any key to continue . . .

Question 8
For this question, you had to implement the operations of a Matrix class template.
(a) The code to be inserted shown in bold.

Discussion:

Until now, we have placed the definition of the class (in the header file) and the definition of the member
functions (in the implementation file) in separate files. However this does not work with class templates. As
shown below both the interface and implementation are within the header file Matrix.h

File name: Matrix.h


#ifndef MATRIX_H
#define MATRIX_H

#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
template<class Object>
class Matrix
{
public:
Matrix( int r = 0, int c = 0 );
void SetValue(Object value, int row, int col);
Object GetValue( int row, int col) const;
int GetRow() const;
int GetCol() const;
void OutPut(ostream & out) const;
76

private:
vector< vector<Object> > array;
int rows;
int cols;
};

template <class Object>


Matrix<Object>::Matrix (int row, int col){
rows = row;
cols = col;
array.resize(row);
for (int r = 0; r < row; r++)
array[r].resize(col);

template <class Object>


void Matrix<Object>::SetValue(Object value, int row, int col){
array[row][col] = value;
}

template <class Object>


Object Matrix<Object>::GetValue(int row, int col) const{
return array[row][col];
}

template<class Object>
int Matrix<Object>::GetRow() const{
return rows;
}

template<class Object>
int Matrix<Object>::GetCol() const{
return cols;
}

template <class Object>


void Matrix<Object>::OutPut(ostream & out) const{
for (int r = 0; r < rows; r++){
for(int c = 0; c < cols; c++){
out<<array[r][c]<<'\t';
}
cout<<endl;
}
}

template<class Object>
Matrix<Object> operator+(const Matrix<Object> & x,
const Matrix<Object> & y){
int xrow = x.GetRow();
int xcol = y.GetCol();
assert( xrow == y.GetRow() && xcol == y.GetCol());
Matrix<Object> temp(xrow,xcol);
for (int r = 0; r < xrow; r++){
for(int c = 0; c < xcol; c++){
Object sum = x.GetValue(r,c) + y.GetValue(r,c);
temp.SetValue(sum, r, c);
}
}
return temp;
77 COS112V/101/3/2009

#endif

(b) For this question you had to write a test program for your Matrix class:

#include <iostream>
#include "Matrix.h"
using namespace std;

int main() {
Matrix<int> M1(2,2);
Matrix<int> M2(2,2);

M1.SetValue(1,0,0);
M1.SetValue(2,0,1);
M1.SetValue(3,1,0);
M1.SetValue(4,1,1);

M2.SetValue(5,0,0);
M2.SetValue(6,0,1);
M2.SetValue(7,1,0);
M2.SetValue(8,1,1);

Matrix<int> M3(2,2);
M3 = M1 + M2;

M1.OutPut(cout); cout<<endl;
M2.OutPut(cout);cout<<endl;
M3.OutPut(cout);cout<<endl;

return 0;
}

Output Produced:
1 2
3 4

5 6
7 8

6 8
10 12

Press any key to continue . . .

Note:
As shown above - we also have the possibility to write class templates, so that a class can have members that use
template parameters as types. C++ class templates are used where we have multiple copies of code for different
data types with the same logic. If a set of functions or classes have the same functionality for different data
types, they become good candidates for being written as templates. C++ class templates are ideal for container
classes (a class of objects that is intended to contain other objects). Examples of container classes will be the
STL classes like vector (chapter 8, Savitch), and list. Once the code is written as a C++ class template, it
can support all data types. (See section 17.2, Savitch for full explanations on Class Templates.) For instance the
Matrix template above can accommodate a Matrix of any type, be it strings, doubles, ints, etc.

Savitch limits his discussion to popular member functions of the STL vector class, such as push_back (page
513), size (page 513), capacity (page 517), reserve (page 517) and resize (page 518). However there
78

are other member functions such as:


empty which returns true if the vector is empty and false otherwise
pop_back which removes the last element of a vector
back which returns the last element of the vector

© Unisa

2008

Das könnte Ihnen auch gefallen