Professional Documents
Culture Documents
School of Computing
Bar code
CONTENTS
1 INTRODUCTION AND WELCOME .................................................................................................... 4
6.4 WORKSHOP..................................................................................................................................... 12
8 ASSESSMENT ................................................................................................................................. 13
9 EXAMINATIONS .............................................................................................................................. 41
Please note / important note: COS1512 is a semester module. You need AT LEAST eight hours
per week for this module.
If you do not receive your study material immediately after registration, you have to download it
from the Internet so that you are able to start IMMEDIATELY with your studies. See this tutorial
letter for details about the downloading of study material.
To gain admission to the examination you have to submit Assignment 1 in time. The due
date is 17 February if you are registered for the first semester and 10 August if you are
registered for the second semester.
The COSALLF/301/0/2012 tutorial letter contains important general information that you will need
during the year such as the names and contact details of lecturers assigned to the different
modules
3
1 INTRODUCTION AND WELCOME
Dear Student,
Welcome to COS1512. Up to 2010, this module has been known as 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.
In this module we assume that you have mastered the study material covered in COS1511 (known
as COS111U up to 2010). If you have not passed COS1511 yet, we strongly advise you to
consider cancelling your registration for COS1512 for the following reasons:
• The time constraints of the semester system make it very difficult to master two
programming modules at the same time.
• The study material covered in COS1512 builds on what was done in COS1511. If you
have not yet passed COS1511, you will constantly have to refer back to the COS1511
study material which will make it all the more time-consuming and difficult to master
COS1512.
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!
When you register, you will receive an inventory letter containing information about your tutorial
matter. See also the booklet entitled my Studies @ Unisa, (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 +27 12 429 4104 or 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.
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.
2.1 Purpose
COS1512 is one of a number of first-year Computer Science modules offered by the School of
Computing at Unisa.
The paragraphs below show where COS1512 fits into the programming modules offered by the
School of Computing:
• COS1511 (known as COS111U up to 2010) deals with the basic concepts of programming,
using the programming language C++. It is aimed at students who have not done any
programming before.
5
• COS1512 introduces the learner to objects and the object-oriented programming
environment. It assumes that you have completed COS1511 or have an equivalent
programming qualification. We refer you to Part 2, Section C of the Unisa Calendar.
• COS1521 provides a general background to computer systems.
• INF1511 is an introductory course in Delphi programming.
• COS1501 introduces the mathematics relevant to Computer Science.
2.2 Outcomes
Once you have completed this module, you should have reached the following outcomes:
Outcome 1:
You should be able to design a logical solution to a simple programming problem,
making appropriate assumptions.
Assessment criteria:
Through assignments, including multiple choice and written assignments and an examination at
the end of the semester, you are assessed on your ability to:
• interpret a problem description which specifies the requirements of a program;
• identify all steps necessary to solve a problem and order the steps in the correct logical
sequence;
• write down the logical sequence of operations that a computer should perform to solve a
particular problem;
• apply object-oriented principles during problem solving.
Outcome 2:
You should be able to write C++ program code, demonstrating the principles of good programming
style.
Assessment criteria:
Through assignments, including multiple choice and written assignments and an examination at
the end of the semester, you are assessed on your ability to:
• use the different C++ programming constructs appropriately and correctly, in order to
implement a solution to a programming problem;
• write functions and use them in a program;
• define classes and use object-oriented principles to implement programming problems;
• recognise/locate errors in a program and correct them.
Outcome 3:
You should be able to demonstrate an understanding of the theory underlying the basic
programming concepts.
Assessment criteria:
Through assignments, including multiple choice and written assignments and an examination at
the end of the semester, you are assessed on your ability to:
• explain the purpose of a particular C++ programming construct and identify problem
descriptions where they are applicable;
• define relevant programming concepts.
The specific learning objectives for each chapter in the prescribed book for COS1512 in order to
reach the above learning outcomes are given in more detail in the study guide included in
Appendix F of this tutorial letter.
6
COS1512/101
3.1 Lecturer
If you experience problems with this subject or have any other enquiry about it, please feel free to
contact the lecturers. The names and telephone numbers of your lecturers for this module, as well
as the module e-mail address you can use for any queries regarding this module, are supplied in
tutorial letter COSALLF/301/0/2012.
Email: Email is a convenient and the most effective way of communicating with a lecturer.
Students registered for the first semester should send e-mail queries to
COS1512-12-S1@unisa.ac.za
and students registered for the second semester should send e-mail queries to
COS1512-12-S2@unisa.ac.za.
Do not email the lecturer directly - rather use the module email address, as a specific lecturer may
not be available. Using the module email ensures someone will read it. Include the module code
and your student number in the subject header of the message. Ask specific questions. It is
difficult to respond properly via email to a request such as 'I don't understand problem 5.1. Please
explain.' Always state exactly what it is that you do not understand.
Phone us: You are welcome to phone us directly, but please consult your tutorial letters and the
myUnisa discussion forum to ensure that your query has not already been addressed. We are
sometimes unavailable due to other departmental, research or university duties. If you fail to
reach us directly, please phone the secretary. In urgent cases you may also leave a message at a
secretary for us to call you back. The best contact hours are between 9:00 and 13:00 in the
mornings, except Wednesdays when we have our departmental meetings
3.2 Department
The School of Computing can be contacted telephonically at (012) 429 6122. Should you be
unable to reach any of the lecturers for COS1512, 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.
3.3 University
Lecturers for this module are only responsible for content-related queries about the study material
used for COS1512.
If you need to contact the University about matters not related to the content of this module,
please consult the publication my Studies @ Unisa 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).
7
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. See
the brochure my Studies @ Unisa for contact details.
Walter Savitch. Problem Solving with C++, 8th edition. Pearson International Edition: Addison-
Wesley, 2012.
You may also use the 7th 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 my Studies @
Unisa. If you have any difficulties with obtaining books from these bookshops, please contact
vospresc@unisa.ac.za.
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.
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:
8
COS1512/101
•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 COS1512 and follow
the instructions.
Appendix A of this tutorial letter contains more instructions on the use of the C++ software.
4.4 E-reserves
Content-related queries should be posted on the cos1512 discussion forum on myUnisa rather
than sent to the cos1512 e-mail address. In this way fellow students can also contribute and
benefit.
6.1 Syllabus
Chapter 8 8.1 and 8.3, plus the subsection Converting Between string Objects and C
Strings, thus excluding 8.2 with the exception of the subsection Converting
9
Between string Objects and C Strings
Note that some of the sections (in Chapters 1, 4 and 5) are omitted, because they have already
been covered in COS1511. The other sections that are omitted fall outside the scope of this
module.
We provide two study programmes on the next page, 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.
10
COS1512/101
11
6.3 Hints on studying this module
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 COS1512 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.
6.4 Workshop
A practical workshop on objects is offered in Pretoria during March (for first semester students)
and August/September (for second semester students) to assist you in mastering the basic
principles regarding objects before / while attempting assignment 2. The invitation to the workshop
(Tutorial Letter 102) includes the questions you will do in the computer laboratory under assistance
from lecturers. The solution to these questions (Tutorial Letter 103) will be distributed to you after
the workshop and be made available online as well.
All COS1512 students must have access to a computer running Windows. The computer must
have a CD-ROM drive. Note that Windows XP is the default operating system supported by
Unisa. 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. We also include
instructions on installing the prescribed software on Windows 7 in Appendix C.
12
COS1512/101
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.
8 ASSESSMENT
8.1 Assessment plan
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. The
assessment criteria for each assignment correspond to a large extent to the learning outcomes
specified in the study guide (Appendix F) for the study material covered by the assignment.
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, Appendix F,
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.
13
You will receive tutorial letters (201 and 202) discussing each assignment. The solution to
assignment 3 is provided in Appendix E 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.
When we mark assignments, we comment on your answers. Many students make the same
mistakes and consequently we discuss general problems in the solutions to the assignments. As
mentioned before, it is therefore, important to work through these tutorial letters and to make sure
you understand our solutions and where you went wrong.
The marks you obtain for an assignment are converted to a percentage. If you for instance
obtained 25 marks out of a possible 50 marks for Assignment 1, you received 50% for Assignment
1. For Assignment 1 this percentage in turn contributes a weight of 20% to the year mark, and for
Assignment 2 this percentage contributes a weight of 80% to the year mark.
If a question is not marked, we will still award some marks if you attempted this question (note that
this is not the way in which questions will be marked in the examination!). We include complete
solutions for all questions.
The marks you receive for programming questions will be determined on the following basis:
Question not done 0
Question attempted, but the program does not work at all 30 - 40% of the marks
allocated to the question
A good attempt, but there are a few problems with your answer 70 - 80% of the marks
allocated to the question
The program works correctly and produces the correct output full marks
Note that not all mistakes are corrected – but we will provide informative comments.
If you do not include the program output, it means there are “a few problems with your answer”
and the maximum you can get is then 70 - 80% of the marks allocated to the question.
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.
Assignment assessment and year mark calculation: Your mark for this module is made up of a
year mark (10%) and an examination mark (90%). The final year mark is calculated based on your
performance in assignments throughout the year. Therefore, assignments not only give you the
opportunity to evaluate your understanding of the materials covered in the module, but also
contribute towards your final mark.
14
COS1512/101
The weights allocated to the assignments for COS1512 are summarized as follows:
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:
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.
The following formula will be used to calculate your final year mark:
Year mark (out of 100) x 10% + Examination mark (out of 100) x 90%
Assignments are numbered consecutively starting from 01 using Arabic numerals. The
assignments are marked and a percentage is awarded according to your achievement. These
assignments have a very important learning function. Please attempt (not necessarily submit) all
assignments, and compare them to the solutions provided.
15
8.4 Due dates of Assignments
The table below gives the due dates of the assignments for this module. Do not submit
assignment 3 - it is a self assessment assignment.
Assignment Due Date Semester 1 Due Date Semester 2 Weight
01 17 February 10 August 20%
02 23 March 7 September 80%
03 27 April - do not 12 October - do not Self Assessment
submit submit
Due to regulatory requirements (imposed by the Department of National Education) the following
applies: To gain admission to the examination you have to submit Assignment 1 in time. The due
date is 17 February if you are registered for the first semester and 10 August if you are registered
for the second semester.
You may submit written assignments and assignments either by post or electronically via
myUnisa. For detailed information and requirements as far as assignments are concerned, see my
Studies @ Unisa, which you received with your study package. Follow the instructions given in
Tutorial Letter COSALLF/301/4/2012, as well as the brochure my Studies @ Unisa, 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.
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.
16
COS1512/101
8.6 Assignments
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 that will calculate the salary for employees at the High Fashion retail store. The
program must use two overloaded functions, each named calcSalary. The first function must
calculate the salary for a permanent employee. It will have one parameter of type char
representing the type of duties that the employee performs. The second function will calculate the
salary for a temporary employee. It will have a parameter of type char representing the duties of a
temporary worker and a second parameter of type int representing the number of hours that the
employee works per month.
The main function should request the user to specify whether the worker is a permanent
employee (represented by the character ‘p’) or temporary employee (represented by the
character ‘t’). The user should then be asked to enter the type of duties performed by the
employee. The possible duties for permanent employees are sales, represented by the character
‘s’ or stock control, represented by the character ‘c’. The possible duties for temporary
employees are merchandising, represented by the character ‘m’ or stock counting, represented
by the character ‘c’. If the employee is temporary, the user must be asked to input the number
of hours that the employee works per month as well. Temporary employees either work 60 hours
or 102 hours per month. The main function should then call the correct overloaded function and
display the salary.
17
17.90 and TEMP_PER_HOUR_COUNT with a value of 16.80, representing the rate per hour to
be used in the calculation of the salary for permanent and temporary employees respectively
according to their duties. Also define an int constant variable PERM_HOURS with a value of 192
representing the number of hours that a permanent employee works per month.
Question 2
The CrazyCopy printing business gives a bonus to employees when they go on pension. They
get R500 for the first 10 years’ service, and R5 for every month after that. If they have less than 5
years’ service they only get R5 per month’s service. Write a program that converts 2 dates (mm
yyyy) to month format. The program must ask for the month and year that the employee started at
the company and his last month and year in service. Read the month and year of each date
separately. It must then convert both dates to months, calculate the difference, determine the
bonus to be paid, and display the number of years and months he was employed by the company
plus the bonus that must be paid to him. The program must check that the user has entered the
dates in the correct order. Verify that the months entered are legitimate months, using the assert
function. Assume that only years between (and including) 1975 and 2010 are valid, e.g. 13 1991,
and 7 1966 are not valid dates.
Question 3
The grade 7 mathematics class of Sunnyside Primary are doing an interesting project on operator
precedence. The class is divided into groups. Each member in each group must say how they
want the following calculation to be done by supplying operator precedence:
y = 14 * 9 – 8 / 2 + 10 / 3 – 8 + 4;
For example, if Peter wants division to be done first, then addition, then subtraction and then
multiplication, the statement will look as follows:
There are 24 possible combinations of these operators. Peter’s group has chosen combinations 3,
8, 7, 1, 2 and 4. The preference of the members of a specific group is saved in an input file
precedence.dat as follows:
Peter 3 / + - *
Dahne 8 + - / *
Renee 7 - * + /
Charl 1 * / + -
Johan 2 / - * +
Sipho 4 * - / +
You have to write a program that will read the file line by line and supply the correct bracketed
assignment statement depending on the combination number that was chosen. The team member
name, the precedence of the operators and the value for y must be written to the output file
results.dat so that the teacher can check if the answer is correct according to the precedence
chosen. If your program works correctly, the output file will look as follows:
Peter / + - * y = -140
Dahne + - / * y = 0
Renee - * + / y = -1
Charl * / + - y = 107
18
COS1512/101
Johan / - * + y = 56
Sipho * - / + y = 61
Create the input file precedence.dat. Use a string variable to read in the team member’s
name, an int variable to read the combination number and variables of type char to read in the
operators. You can assume there will only be 6 records for the purpose of the calculation, but your
program must determine when the end of the file is reached without testing that 6 records have
been read. For the purpose of the program we give you part of the switch statement. Assume
that we are only working with these 6 combinations and complete the switch statement by
supplying the assignment statements with the correct bracketing according to the combinations
supplied above in precedence.dat.
Question 4
Write a program that will read an input file rhyme.txt character by character. The program must
create an output file changed.txt with all lines left-justified, i.e. the program must ignore all
blank characters preceding the first non-blank character in each line. Also change all characters to
upper case.
Create the input file rhyme.txt with the following nursery rhyme:
19
Along came a bunny
And what do you suppose?
Question 5
(a) For each of the following, write a single C++ statement that performs the identified task.
Assume that variables total and interest have been defined as type double, and that
total has been initialised as 1000.00 and interest as 0.30.
(i) Declare two variables fPtr1 and fPtr2 to be pointers to objects of type double.
(ii) Let the pointer fPtr1 point to the double object total.
(iii) Print the contents of fPtr1.
(iv) Let the pointer fPtr2 point to the double object interest.
(v) Add the value of the object pointed to by fPtr2 to the value of the object pointed to by
fPtr1.
(vi) Let pointer fPtr2 point to the same location as fPtr1.
(vii) Print the contents of fPtr2.
(viii) Print the value of the object pointed to by fPtr1.
20
COS1512/101
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
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;
21
• 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:
Question 2
class Date{
public:
//constructors
Date();
Date(int day, int month, int year);
//inspectors
int GetDay() const;
int GetMonth() const;
int GetYear() const;
//mutators
void SetDay(int day);
void SetMonth(int month);
void SetYear(int year);
//operators to calculate next and previous days
Date &operator++();
Date &operator--();
bool operator<(const Date &d);
private:
//return the length of current month, taking into
//account leap years
int MonthLength();
//the current day month and year
int theday;
int themonth;
int theyear;
};
Implement and test the Date class, taking the following guidelines into account:
22
COS1512/101
c) The functions GetDay(), GetMonth() and GetYear() should return the current day,
month and year respectively.
d) The functions SetDay(), SetMonth() and SetYear() should change the current day,
month or year to the given value.
e) The operator ++ should advance the date by one, and return the new date.
f) The operator B should set the date back by one day, and return the new date.
g) The operator < should calculate whether the receiving date object (left argument) precedes
the parameter date (right argument).
For example, Date(1,1,2002) < Date(1,3,2002).
h) The private member function MonthLength() should return the length of the current month,
taking into account leap years. A year is a leap year if it is either (i) divisible by 4, but not by
100, or (ii) divisible by 400. In a leap year, February has 29 days, otherwise it has 28 days.
i) Also overload the insertion operator << to output a date to the screen. For example, the date
in (a) above should be written as: 14 September 1752.
Question 3
Turn the Date class from question 2 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.
Now test the Date class in a C++ program that will do the following:
• Declare a new Date object called d1.
• Display the day, month and year of d1 on the screen.
• Change the date to 28 February 2000.
• Advance this date by one and display the new date on the screen.
• Now change the date to 1 January 2002.
• Set this date back by one and display the new date on the screen.
• Finally change the date to 31 December 2002.
• Advance this date by one and display the new date on the screen.
• Declare a second date object d2(1,1,2003).
• Determine if d1 is earlier than d2 and write the result on the screen.
Question 4
Define a class Pairs as an ADT that uses separate files for the interface and the implementation.
Objects of type Pairs can be used in any situation where ordered pairs are needed. This class
has the two integer data members, f and s, where f represents the first value in the ordered pair
and s represents the second value in the ordered pair:
The class should contain a default constructor that initializes both data members to 0, and two
overloaded constructors, one with one int parameter and the other with two int parameters.
The one-parameter constructor should initialise the first member of the pair; the second member of
the pair is to be 0. The two-parameter constructor should initialise both members of the ordered
pair.
The class should also contain a destructor that outputs the message "Goodbye!".
23
Include accessor functions that return the values stored in each of the member variables of an
object of class Pairs (i.e. get functions), as well as mutator functions to update each of the
member variables of an object of class Pairs respectively (i.e. set functions with a parameter to set
each member variable to a value specified by the parameter). The class should also contain a
void member function called reset() that resets the member variables of a Pairs to values specified
by parameters.
Overload the stream extraction operator >> and the stream insertion operator << as friend
functions so that objects of class Pairs are to be input and output in the form (5,6) (5,-4) (-
5,4) or (-5,-6).
Overload binary operator + as a friend function to add pairs according to the rule
(a,b) + (c,d) = (a + c, b + d)
Overload operator – as a friend function in the same way, i.e. according to the rule
(a,b) - (c,d) = (a - c, b - d)
Overload operator * as a friend function on Pairs and int according to the rule
(a,b) * c = (a * c, b * c)
Write a program to test all the member functions and overloaded operators in your class definition.
Question 5
Overload the +, - and * operators for objects of class Pairs in question 4, as member
functions. Use separate compilation and the same program as in question 4 to test these member
functions.
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 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
Enrichment exercise:
Adapt the application program to use a vector instead of an array. It should not be necessary to
change the class interface or implementation file in any way.
24
COS1512/101
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
The ValueForMoney butchery has a special discount for senior citizens on the Combo Pack and
the Bumper Pack. Write a program that will calculate the amount to be paid after discount. The
program must use two overloaded functions, each named calcAmount. The discount on the
Combo Pack, containing a variety of types of meat, is 15%. The Bumper Pack either consists of
lamb or of beef. The discount for the lamb Bumper Pack is 12%, while the discount for the beef
Bumper Pack is 16%. The first function must calculate the amount to be paid after discount for the
Combo Pack, and will have one parameter of type int representing the number of Combo Packs
required. The second function must calculate the amount to be paid after discount for the Bumper
Pack and will have one parameter of type int representing the number of Bumper Packs
required and one parameter of type char representing whether the packs should contain beef or
lamb (‘b’ for beef and ‘l’ for lamb).
The program must determine which Pack is required, call the appropriate function depending on
the input and display the amount to be paid after discount. Define any variables that you may
need. Also define the following constant variables of type double in your program:
DISCOUNT12 with a value of 0.12
DISCOUNT15 with a value of 0.15
DISCOUNT16 with a value of 0.16
BUMPER_BEEF with a value of R120.00
BUMPER_LAMB with a value of R160.00
COMBO with a value of R130.00
25
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
Write a program that will calculate a student’s year marks for all his subjects. The program must
read the subject code, the assignment marks for two assignments and the percentage that each
assignment contributes towards the year mark, for each subject that the student is registered for.
Create an input file called assignments.dat that contains the following information for a specific
student:
COS1511 30 66 70 49
COS1512 25 76 75 67
COS1521 10 58 90 62
COS1501 50 62 50 57
INF1501 40 82 60 78
INF1511 20 24 80 55
The first field in each line represents the subject code, followed by the percentage that assignment
1 contributes towards the year mark and the student’s percentage for assignment 1. Then follow
the percentage that assignment 2 contributes towards the year mark and the student’s percentage
for assignment 2. You should not count the number of entries in the file to determine how many
times the file must be read.
Your program must read the file line by line, calculate the student’s year mark for the subject as a
percentage and write the subject code and the year mark to an output file yearmark.dat. If your
program works correctly, the output file will look as follows:
COS1511 54.10%
COS1512 69.25%
COS1521 61.60%
COS1501 59.50%
INF1501 79.60%
INF1511 48.80%
Question 4
You have to write a program to read an input file character by character to help Peter solve the
following activity in his activity book. The paragraph below is given:
We h2pe that 32u e5723ed the acti4it3. A6ter 32u ha4e c2mpleted the
acti4it3, 0e5d 32ur re0ult t2: The Acti4it3 C2mpetiti25, Bett3 Da4i0
0treet 99, Auckla5d Park, 8989, a5d 0ta5d a cha5ce t2 wi5 a hamper
c250i0ti51 26 c2l2uri51 a5d acti4it3 b22k0, c2l2uri51 pe5cil0 a5d pe50.
Create an input file activity.dat with the paragraph above. The numbers 0 to 7 have to be
replaced as follows:
0 must be replaced by s
26
COS1512/101
1 must be replaced by g
2 must be replaced by o
3 must be replaced by y
4 must be replaced by v
5 must be replaced by n
6 must be replaced by f
7 must be replaced by j
Ask the user to input the names of the input and output files. Read the input file character by
character, and write the character (if it stays the same) to the output file, or write the changed
character to the output file. Call your output file competition.txt.
Question 5
(a) For each of the following, write a single C++ statement that performs the identified task.
Assume that variables examMark and yearMark have been defined as type double, and
that examMark has been initialised as 67 and yearMark as 58.
(i) Declare two variables fPtr1 and fPtr2 to be pointers to objects of type double.
(ii) Let the pointer fPtr2 point to the double object yearMark.
(iii) Print the address of the object pointed to by fPtr2.
(iv) Print the value of examMark.
(v) Let the pointer fPtr1 point to the double object examMark.
(vi) Change the value of the object pointed to by fPtr1 to be the average of examMark and
the value of the object pointed to by fPtr2.
(vii) Print the address stored in fPtr1.
(viii) Print the value of the object pointed to by fPtr2.
(b) Use diagrams similar to display 9.1 in Chapter 9 in Savitch to trace and give the output of
the following program.
#include <iostream>
int main()
{
int value1 = 20;
int value2 = 30;
int *ptr2 = &value1;
int *ptr1 = &value2;
*ptr1 -= *ptr2;
ptr1 = ptr2;
cout << *ptr1 << endl;
cout << *ptr2 << endl;
return 0;
}
27
ASSIGNMENT 2 (SECOND SEMESTER)
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
Turn the employee record into a class type rather than a structure type. The employee record
class should have private member variables for all the data. Include public member functions for
each of the following:
• a default constructor that sets the employee‘s first name and last name to a blank string, and
his annual salary 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);
Embed your class definition in a test program. The test program should create two Employee
objects and display each object’s annual salary. Use the overloaded constructor to initialise one of
the Employee records as Joe Soap with a annual salary of R1456.00. Obtain the following input
values for the other Employee record from the keyboard:
Joanne Soape
R15446.66
Now give each employee a 10% raise and display each Employee object’s annual salary again.
28
COS1512/101
Question 2
The questions below refer to the following class declaration:
#include <iostream>
#include <string>
using namespace std;
class Chequebook
{
public:
Chequebook();
Chequebook(float AccountBalance);
void Deposit (float Amount);
void WithDraw (float Amount);
float CurrentBalance() const;
void Adjust();
private:
float Balance;
};
int main()
{
cout << "Enter the Account balance:";
float amount;
cin >> amount;
Chequebook Chequebook1(amount);
cout << “Account balance: R “ << Chequebook1 << endl;
cout << “Enter amount to deposit:”;
cin >> amount;
Chequebook1.Deposit(amount);
cout << “Balance after deposit: R” << Chequebook1 << endl;
cout << “Enter amount to withdraw:“ ;
cin >> amount;
Chequebook1.WithDraw(amount);
cout << “Balance after withdrawal: R “ << Chequebook1 << endl;
++Chequebook1;
cout << “Balance after adjusting: R” << Chequebook1;
return 0;
}
(a) What is the purpose of the keywords public and private in the class declaration?
(b) What is the purpose of a constructor?
(c) Give implementations of both the default constructor and the second constructor.
(d) Implement the Deposit() and WithDraw() member functions. The Deposit()
member function should increment the member variable Balance with the amount
deposited, and the WithDraw() member function should decrement the member variable
Balance with the amount withdrawn.
(e) Implement the CurrentBalance() member function. It should return the current balance
of the cheque book.
(f) The member function Adjust() should increment the member variable Balance by R100.
Give an implementation for this member function.
29
(g) Overload the stream insertion operator as a friend function. It should write the balance of the
account to the given output stream.
(h) The statement ++Chequebook1; should increment the member variable Balance of
Chequebook1 by R100. Give three different implementations for the overloaded operator ++
to accomplish this:
• using the member function Adjust()
• implementing the overloaded operator ++ as a friend function
• implementing the overloaded operator ++ as a member function. Hint: See chapter 11
in the study guide, Appendix F.
(i) Run your program three times (each time with a different version of the overloaded operator
++; comment the other two versions out during each run) with the following input:
400
200
300
Question 3
Turn the Chequebook class from question 2 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 4
Define a class RewardCard as an ADT that uses separate files for the interface and the
implementation. The class represents a card on which members can earn points, which are in turn
converted to vouchers. This class has four member variables:
• name, a string that holds the name of the member
• id, a string containing 6 digits to identify the member uniquely
• store, a string representing the store for which this card is valid
• points, an int representing the number of points that the member has earned.
The class should contain a default constructor that initializes name and store to an empty strings,
id to a string containing six 0's and points to 0. It should also contain an overloaded constructor
that initialises a new member’s name, ID and the store and sets points to 0. The destructor
should not perform any action.
Include accessor functions that return the values stored in each of an object of class
RewardCard’s member variables respectively (i.e. get functions), as well as mutator functions to
update each of the member variables of an object of class RewardCard respectively (i.e. set
functions with a parameter to set each member variable to a value specified by the parameter).
Overload the equality operator == as a friend function for class RewardCard. This function
returns true if the name, id and store member variables of card1 is identical to those of
card2 and false otherwise. Use the following prototype:
bool operator==(const RewardCard & card1, const RewardCard & card2)
Also overload the + and – operators for class RewardCard as friend functions. Operator + is
used when a person uses the reward card to purchase goods. Operator + should add the values of
the points member variables of two RewardCard objects if the name, id and store member
variables of the two RewardCard objects are identical. Operator + should return an object of type
RewardCard with the same values for the name, id and store member variables as the two
30
COS1512/101
operands. Use the equality operator == for RewardCard and the assert macro to check that the
operands for the overloaded + operator are identical.
Similarly, operator – is used to determine the difference between points when a person returns
goods that had earned points with the reward card. Operator - should subtract the values of the
points member variables of two RewardCard objects if the name, id and store member
variables of the two RewardCard objects are identical. Operator - should return an object of
type RewardCard with the same values for the name, id and store member variables as the two
operands. Again, use the equality operator == for RewardCard and the assert macro to check
that the operands for the overloaded – operator are identical.
Also define an overloaded prefix operator ++ (implemented as a friend function) to add bonus
points to the card. Operator ++ should add 100 points to the points member variable of the
RewardCard object.
Overload the stream extraction operator >> and the stream insertion operator << as friend
functions for class RewardCard. The stream insertion operator << should print a voucher for the
object. The voucher should display the name, ID, store and an amount for which it can be traded
at the relevant store, or a message in the case of insufficient points earned. Once a card has more
than 500 points, the points can be converted to an amount for which it can be traded at the
relevant store. 100 points is equal to R1.00. If a card has less than 500 points, the voucher will
display the message "Sorry, this is not enough points yet for a voucher! Keep on buying". Use the
following prototype:
ostream& operator << (ostream& outs, const RewardCard & RC)
int main() {
RewardCard ACard;
RewardCard MyCard("Hansie", "111111", "OurStore", 100);
cout << "This is ACard: " << ACard << endl;
cout << "This is MyCard: "<< MyCard << endl;
31
cout << "After giving Hansie 200 bonus points:" << endl;
cout << MyCard << endl;
//Hansie returned goods which has earned 100 points - this must now be
//deducted
cout << "Enter details for return of goods with points value of 100 "
<< "points:" << endl;
cin >> ACard;
MyCard = MyCard - ACard;
cout << "Result after deducting 100 points:" << endl << MyCard <<
endl;
return 0;
}
Supply appropriate input values for the two input statements (cin >> ACard;) according to the
comments in the program.
Question 5
Overload the +, - and ++ operators for objects of class RewardCard in question 4, as member
functions. Use the same program as in question 3 to test these member functions.
Question 6
Overload the stream extraction operator >> for the class Employee in Question 1 to read values
for an object of class Employee from a file. Also overload the stream insertion operator << to
print the data for an employee record 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 employees from a file named Employees.dat into an array. Assume that the file
will never contain data for more than 20 employees. Use the array to determine the average
salary, as well as the highest salary and the lowest salary. Display the average salary, the highest
salary and the lowest salary on the screen. Increase each employee’s salary by 10 % and use the
overloaded stream insertion operator << to display the updated Employee objects on the screen
and also to write the updated Employee objects to a new data file. Use the following data:
Enrichment exercise:
Adapt the application program to use a vector instead of an array. It should not be necessary to
change the class interface or implementation file in any way.
33
SELF ASSESSMENT ASSIGNMENT 3 (SEMESTER 1 AND SEMESTER 2)
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.
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:
35: void setY();
37:};
38:
39:void B::setY()
35
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.
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;
36
COS1512/101
private:
string publisher;
Date date;
string 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 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.
(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;
};
37
(iv) Output all the details of Magazine M.
(v) Write a statement to overload operator<< as a friend function to the class Book and
insert the following implementation to your code:
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 );
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;
38
COS1512/101
private:
vector< vector<Object> > array;
int rows;
int cols;
};
39
}
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
40
COS1512/101
9 EXAMINATIONS
A 2 hour examination will be scheduled for this module. Please refer to the my Studies @ Unisa
brochure for general examination guidelines and examination preparation guidelines.
What if there are mistakes in the marking of assignments? (Do NOT re-submit to
Assignments Department!)
We use a team of external markers that are sub-contracted for the purpose of marking
assignments during the year. There are close to 300 students enrolled for the module. For this
reason, inconsistency in the marking style of individual markers may be encountered. We request
that students only query assignment marking where the marks will change significantly (i.e. more
than 5%). Please follow the RE-MAIL PROCEDURE below should you require that an assignment
be remarked. If your marks are added incorrectly or a question is not marked which we stated (in
the solutions) was to be marked, or you feel strongly that you were penalised unfairly, follow the
procedure below. If you phone we will just tell you to follow the RE-MAIL PROCEDURE.
41
PO Box 392
Pretoria, 0003
42
COS1512/101
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 DISK2012. It also contains some information regarding
CodeMate, which is offered with the textbook.
Note:
On registration you should receive the tutorial matter listed below:
DISK2012: Prescribed software
COS1512/101/2012: First tutorial letter: General information, study programme, exam admission
and assignments
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 COS1512 tutorial letters will also be available on the Internet.
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 distributed 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.)
43
Please note that you will probably also have problems installing and running Dev-C++ under
Windows Vista and Windows 7. See Appendix B for installing the prescribed software with
Windows Vista and Appendix C B for installing the prescribed software with Windows 7.
In COS1512 you will be writing more complicated programs than in COS1511. 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.
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 “COS1512”.
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";
44
COS1512/101
Uninstalling
To uninstall either the compiler or the IDE, use the Add/Remove Programs facility in the Control
Panel of Windows.
45
• 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!
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\cos1512) in which you save all
your work for a particular module. Navigate to this folder (if necessary) before clicking on the
"Save" button.
46
COS1512/101
Initially the source file is called Untitled1, so the first thing you should do is give it a name. Do this
by choosing "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.
47
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.)
48
COS1512/101
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).
49
Dev-C++" on the "Programs" submenu. Alternatively, you can navigate to the folder
c:\unisa\devcpp and execute the file devcpp.exe
Figure 1
Figure 2
50
COS1512/101
Figure 3
When you create a project as explained above, Dev-C++ automatically produces a source file
(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
51
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)
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
H I
E
F
Figure 4
52
COS1512/101
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.
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.
53
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;
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
54
COS1512/101
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.
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.
55
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.
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.
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.
56
COS1512/101
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
57
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".
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.
FAQ07
When I try to compile and run even a simple program, I receive the following error (the directory
path for the project file is C:\unisa\Assignments, the project is Assignment1 and the source file is
Question1):
mingw32-make.exe C:\unisa\Assignment1\mingw32-make.exe Circular question <- Question1.o
dependency dropped
C:\unisa\Assignment1\makefile.win [Build error] exe: *** [Question 1] Error 1
Answer
If you get any error message referring to the .o file, open a new project, copy or type the
application file into the untitled file that is created automatically when the project opens, and save
it explicitly as a .cpp file. Also save the implementation file for the class used in the project
explicitly as a .cpp file. This usually solves the problem.
58
COS1512/101
1. Install mingw and devcpp as instructed on DISK 2012 (also in Appendix A of this tutorial
letter).
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.
59
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 Dev-C++ 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 Dev-C++ where you can set the initial settings (i.e choose the language
and set up the cache). Once that is done, close Dev-C++ and return to the following window:
3. Now you need to create a shortcut to Dev-C++. To set up the shortcut to Dev-C++ 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
60
COS1512/101
3.7 Right-click on ‘devcpp Application’, choose ‘Send To’ in the pop-up menu and then
‘Desktop (Create shortcut)’ as shown below.
61
3.8 Double-click on the shortcut to activate Dev-Cpp.
62
COS1512/101
Now you need to create a shortcut to Dev-C++. To set up the shortcut to Dev-C++ follow the steps
below:
• Double-click on the "My Computer" icon on your desktop
• Double-click on ”Local Disk C:”
• Double-click on “Unisa”
• Double-click on the Devcpp folder
• Select ‘devcpp Application’ as shown in the window below:
•
63
Right-click on ‘devcpp Application’ and create the shortcut as shown below:
Remember to change the settings as explained in the section “Using the software” on Disk 2012.
After succesfull installation of the software and creating the shortcut on the desktop, please do the
following:
64
COS1512/101
• Click on Apply
• Click on OK
• Now double click on the DEVC++ icon and start creating your program.
3. If error messages do not display when compiling your program, please follow the
steps below:
65
15 APPENDIX D: SOURCE LISTINGS OF THE SAMPLE PROGRAMS IN THE
TEXTBOOK
The source code listings of the sample programs in the 8th edition of the text book can be found at
the Companion Website for the text book. Go to www.pearsinternationaleditions.com/savitch,
select the text book and then click on Companion Website. Click on the Register button, and
type in the student access code found beneath the pull tab of the ONLINE ACCESS card in front
of the text book.
The source code listings of the sample programs in the 7th edition of 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 Dev-C++.
66
COS1512/101
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;
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);
67
//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;
return 0;
}
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)
68
COS1512/101
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)
{
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 in Savitch for more detail.
69
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);
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>
//been rearranged so that v[0] >= v[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
{
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);
}
71
//declare a vector with distinct.size()elements and initialise
//each to 0
vector<int> occurrences (distinct.size());
//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 sort(vector<int>& v)
{
int 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.
}
}
return index_of_max;
}
Please enter list of values. Press 'enter' after each value. Use CTRL Z
to end.
-12
3
-12
4
1
1
-12
1
-1
1
2
3
4
2
3
73
-12
^Z
N Count
4 2
3 3
2 2
1 4
-1 1
-12 4
Press any key to continue . . .
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;
int main() {
cout << "The sum between 13 and 17 is:";
cout << sum (13,17) <<endl;;
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;
74
COS1512/101
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.
Recursively:
sum(m,n) = m + sum(m+1,n)
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,1 sum(13,17) = 75
since m!=n
return 13 + 62 = 75
step a return 13 +
sum(14,17) = 62
sum(14,17)
since m!=n
return 14 + 48 = 62
step b return 14 +
sum(15,17) = 48
sum(15,17)
since m != n
return 15 + 33 = 48
step c return 15 +
sum(16,17) = 33
sum(16,17)
sum(17,17)
since m = n return 17
step e 75
return 17
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.
So eventually the recursive calls will stop at sum(17,17) - because an answer of 17 can be
returned.
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
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>
76
COS1512/101
77
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:
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 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
78
COS1512/101
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:
Study Guide Appendix F, 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;
};
79
#include "Date.h"
#include "Publication.h"
string Publication::GetPublisher()const
{
return publisher;
}
(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>
};
#endif
80
COS1512/101
#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;
}
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
int Magazine::GetIssuesPerYear()const{
return issuesPerYear;
81
}
(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"
return 0;
}
(g) Write a statement to overload operator<< as a friend function to the class Book and insert
the following implementation to your code:
out<<B.GetTitle()<<endl;
out<<B.GetPublisher()<<endl;
out<<B.GetDate()<<endl;
out<<B.getAuthor()<<endl;
out<<B.getISBN()<<endl;
}
class Publication {
public:
Publication(const string & p, const Date & d, const string &
t);
Date GetDate( ) const;
string GetPublisher( )const;
string GetTitle() const;
protected:
string publisher;
Date date;
string title;
};
#endif
83
out<<d.day<<"/"<<d.month<<"/"<<d.year<<endl;
}
#endif
File name:Publication.cpp
#include <iostream>
#include <string>
#include "Date.h"
#include "Publication.h"
using namespace std;
string Publication::GetPublisher()const{
return publisher;
}
Filename: Book.h
#ifndef BOOK_H
#define BOOK_H
#include "Publication.h"
#include "Date.h"
#include <string>
84
COS1512/101
#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;
}
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;
85
};
#endif
Filename: Magazine.cpp
#include "Magazine.h"
int Magazine::GetIssuesPerYear()const
{
return issuesPerYear;
}
Filename: Test.cpp
#include <iostream>
#include "Date.h"
#include "Publication.h"
#include "Book.h"
#include "Magazine.h"
return 0;
}
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.
86
COS1512/101
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>
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};
87
double Doubles[14] = {2.99,8.77,4.88,6.44,3.45};
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;
template<class T>
bool search( T array[], int n, T target)
{
for ( int i = 0; i < n; i++ ){
if (array[i] == target)
88
COS1512/101
return true;
}
return false;
}
//Precondition: the array base type must have operator<< defined,
//&& n <= declared size of the array argument.
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:
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
89
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;
private:
vector< vector<Object> > array;
int rows;
int cols;
};
template<class Object>
int Matrix<Object>::GetRow() const{
return rows;
}
template<class Object>
int Matrix<Object>::GetCol() const{
return cols;
}
90
COS1512/101
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;
}
#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;
91
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
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, size, capacity, reserve and resize. However there 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.
92