COS1512 Tut Letter 101
COS1512 Tut Letter 101
COS1512 Tut Letter 101
Introduction to Programming II
COS1512
Semesters 1 and 2
School of Computing
Please activate your myUnisa and myLife email addresses and ensure you have
regular access to the myUnisa module site COS1512-2019-S1 or COS1512-
2019-S2 as well as your e-tutor group site.
Note: This is a blended online module, and therefore your module is available on
myUnisa. However, in order to support you in your learning process, you will also
receive Tutorial Letter 101 in printed format. Please visit the COS1512 course website
on myUnisa at least twice a week.
BARCODE
CONTENTS
Page
1 INTRODUCTION ............................................................................................................................ 4
2 OVERVIEW OF THE MODULE COS1512 ..................................................................................... 5
2.1 Purpose .......................................................................................................................................... 5
2.2 Outcomes ....................................................................................................................................... 6
3 LECTURER(S) AND CONTACT DETAILS .................................................................................... 7
3.1 Lecturer(s) ...................................................................................................................................... 7
3.2 Department ..................................................................................................................................... 7
3.3 University ........................................................................................................................................ 8
4 MODULE-RELATED RESOURCES .............................................................................................. 8
4.1 Joining myUnisa ............................................................................................................................. 8
4.2 Other resources – Printed support materials .................................................................................. 9
4.3 Prescribed books ............................................................................................................................ 9
4.4 Recommended books ................................................................................................................... 10
4.5 Prescribed software ...................................................................................................................... 10
4.6 myUnisa Forum ............................................................................................................................ 10
4.7 Tutorial letters ............................................................................................................................... 10
4.8 Additional Resources .................................................................................................................... 11
5 STUDENT SUPPORT SERVICES FOR THE MODULE .............................................................. 11
5.1 E-Tutors ........................................................................................................................................ 11
5.2 Downloading study material and software .................................................................................... 12
5.3 Additional Resources on myUnisa ................................................................................................ 12
5.4 Announcements on myUnisa ........................................................................................................ 12
5.5 Installation of the software ............................................................................................................ 12
6 STUDY PLAN ............................................................................................................................... 12
6.1 Syllabus ........................................................................................................................................ 12
6.2 Planning your academic year ....................................................................................................... 13
6.3 Hints on studying this module ....................................................................................................... 15
7 MODULE PRACTICAL WORK AND WORK-INTEGRATED LEARNING ................................... 16
8 ASSESSMENT ............................................................................................................................. 16
8.1 Assessment plan .......................................................................................................................... 16
8.2 General assignment numbers ....................................................................................................... 19
8.2.1 Unique assignment numbers ........................................................................................................ 19
2
COS1512/101/3/2019
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 myUnisa so that you are able to start IMMEDIATELY with your studies. See section 5.3 in
this tutorial letter for details about the downloading of study material.
To gain admission to the examination you have to submit one assignment before a
specific date. The due date is 5 April if you are registered for the first semester and 30
August if you are registered for the second semester.
The COSALLF/301/0/2019 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
Dear Student
Welcome to COS1512. 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. In order to succeed with your studies,
you need to start studying immediately and do the assignments properly.
This 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 and the Study @ Unisa brochure 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.
Because this is a blended online module, you need to use myUnisa to study and complete the
learning activities for this course. You need to visit the website on myUnisa for COS1512
frequently. The website for COS1512 for the first semester is COS1512-19-S1 and for the
second semester it is COS1512-19-S2.
We hope that you will enjoy this module and wish you all the best!
1.1 To get started…
Because this is a blended online module, you need to go online to see your study materials and
read what to do for the module. Go to the myUnisa website here: https://my.unisa.ac.za and log
in with your student number and password. You will see COS1512-19-S1 (for the first semester)
or COS1512-19-S2 (for the second semester) in the row of modules in the orange blocks across
the top of the webpage. Remember to also check in the -More- tab if you cannot find it in the
orange blocks. Click on the module you want to open.
In addition, you will receive a printed copy of this tutorial letter from your module. While the
printed material may appear to be different from the online study materials, they are exactly the
same.
4
COS1512/101/3/2019
additional tutorial letters published on the COS1512 course website under Additional
Resources, containing additional information or solutions to assignments.
When you register, you will receive an inventory letter containing information about your
tutorial matter. See also the brochure entitled Study @ 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.
Some of this study material may not have been available when you registered. Study
material that was not available when you registered will be posted to you as soon as
possible, but is also available on myUnisa.
Please do not contact the School about missing tutorial matter, cancellation of a module,
payments, enquiries about the registration of assignments, and so on, but rather the
relevant department as indicated in the Study @ Unisa brochure. The School should only
be contacted about academic matters.
If you have not received all of the above mentioned tutorial matter, please contact our
DESPATCH DEPARTMENT, using the contact details as given in the Study @ Unisa
brochure. In the meantime, please download the study material from myUnisa.
5
COS1511 deals with the basic concepts of programming, using the programming language C++.
It is aimed at students who have not done any programming before. It is a pre-requisite for
COS1512.
COS1512 introduces the learner to objects and the object-oriented programming environment.
COS1521 provides a general background to computer systems.
INF1511 is an introductory course in Python 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:
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;
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;
6
COS1512/101/3/2019
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;
7
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 Study @ Unisa that you received with your study material. This
brochure contains information on how to contact the University (e.g. to whom you can write for
different queries, important telephone and fax numbers, addresses and details of the times
certain facilities are open).
NB: Always have your student number at hand when you contact the University. Whenever you
write to a lecturer, please include your student number to enable the lecturer to help you more
effectively.
4 MODULE-RELATED RESOURCES
4.1 Joining myUnisa
If you have access to the internet, you can quickly access resources and information at the
University. The myUnisa learning management system is Unisa's online campus that will help
you to communicate with your lecturers, with other students and with the administrative
departments of Unisa.
You can start at the main Unisa website, http://www.unisa.ac.za, and then click on the myUnisa
orange block. This will take you to the myUnisa website. To go to the myUnisa website directly,
go to https://my.unisa.ac.za. Click on the “Claim UNISA Login” on the top of the screen on the
myUnisa website. You will then be prompted to give your student number to claim your initial
myUnisa as well as myLife login details.
This module is presented following a blended approach in the sense that even though you will
still receive some printed study material, most of the information needed to complete this
module is available on myUnisa. myUnisa has inter alia the following tools which you will use
regularly:
Assignments This is a tool to manage your assignments; to submit, track and see
marks obtained.
Official Study Tutorial letters 101 and 301 as well as some past examination papers are
Material available under Official Study Material.
Course Contact The Course Contact tool facilitates e-mail communication between
students and lecturers. Students use their myLife e-mail to send e-mails
to their lecturers through myUnisa.
Frequently Asked Frequently asked questions, or FAQs, are listed questions and answers,
Questions all supposed to be frequently asked in some context, and pertaining to a
8
COS1512/101/3/2019
particular topic.
Learning Units The Learning Units tool contains learning units/lessons for COS1512
and represents the weeks in your study programme. Please use the
weekly Learning Units to guide you in your studies.
Please consult the publication Study @ Unisa which you received with your study material for
more information on myUnisa.
4.2 Other resources – Printed support materials
Because we want you to be successful in this blended online module, we also provide you with
Tutorial Letter 101 in printed format. This will allow you to continue studying and do the
assignments, even if you are not online.
Tutorial Letter 101 will be sent to you at the beginning of the semester, but you do not
have to wait to receive it to start studying – You can go online as soon as you register
and all your study materials will be there.
Therefore, Tutorial Letter 101 is not something that you need to wait for before you start
with the module. It is only an offline copy of the formal content for the online module.
This will give you the chance to do a lot of the studying for this module WITHOUT going
online. This will save you money, of course, and you will be able to take as much time as
you need to read -- and to re-read -- the materials and do the activities.
It is therefore very important that you log into myUnisa regularly. We recommend that you
should do this at least every week, and preferably twice a week, to check for the following:
Check for new Announcements. You can also set up your myLife email so that you
receive the Announcement emails on your mobile device.
Do the Discussion forum activities. For every unit in this module, we want you to share
with the other people in your group in the activities. You can read the instructions there,
and even prepare your answers but you need to go online to post your messages.
Do other online activities. For some of the unit activities, you need to post something
on the Blog or take a quiz or complete a survey in Self Assessment. Don't skip these
activities because they will help you to complete the assignments and activities for the
module.
We hope that this system will help you to succeed in this blended online module by giving you
extra ways to study the materials and practice with all of the activities and assignments. At the
same time, you MUST go online in order to complete the activities and assignments on time --
and to get the most from the online course.
Remember, the printed support materials are a back-up to everything that is found online, on
myUnisa. There are no extra things there. In other words, you should NOT wait for the
Printed support materials to arrive to start studying.
9
Walter Savitch. Problem Solving with C++, 10th edition. Pearson International Edition: Addison-
Wesley, 2018.
You may also use the 7th, 8th or 9th 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 Study @
Unisa. If you have any difficulties with obtaining books from these bookshops, please contact
[email protected].
We will refer to the prescribed book as Savitch.
4.4 Recommended books
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. 8th edition. Prentice Hall, 2008.
John R. Hubbard. Programming with C++. 2nd edition. Schaum’s Outlines, 2000.
4.5 Prescribed software
The prescribed software for this module is Code::Blocks 10.05. We will refer to the software as
Code::Blocks. Code::Blocks includes the MinGW C++ compiler and an Integrated Development
Environment (IDE), which we use to create program files. The prescribed software is provided
on the CD Disk2019 that you should have received in your study package when you registered.
The Disk2019 contains instructions on how to install the software, and how to use the IDE to
write, compile and execute your programs. Click on the link for COS1512 and follow the
instructions.
If you did not receive Disk2019 upon registration, you should download the software
immediately from myUnisa so that you are able to start with your studies at once. The
software is available under Additional Resources on the COS1512 webpage.
4.6 myUnisa Forum
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. You can also contact the e-tutor to whom you are allocated with content-related queries
(see section 5.1).
4.7 Tutorial letters
In addition to the Study Guide, the software and this tutorial letter, there will be other tutorial
letters during the course of the semester. Some will provide additional information (Tutorial
Letters 102, 103, etc.) whilst others will discuss Assignments 1 and 2 (Tutorial Letters 201 and
202). All tutorial letters will be available on myUnisa under Additional Resources. Note also that
the solutions to the self-assessment assignment - Assignment 3 - are available online on the
COS1512 website.
You only receive a printed copy of this tutorial letter (Tutorial Letter 101). All subsequent
tutorial letters are only available on myUnisa under Additional Resources.
10
COS1512/101/3/2019
11
5.2 Downloading study material and software
One of the requirements for study at the School of Computing is to have regular internet
access to access myUnisa and your myLife e-mails. You are therefore expected to
download any study material from the Internet that, for whatever reason, is not available
on paper in time. You may download it from myUnisa. The study material is updated regularly,
thus you need to check the COS1512 website at least twice a week on myUnisa.
Because COS1512 is a semester module, time is of the utmost importance. You should start
studying the module immediately after registration. This tutorial letter, the Study Guide and the
software are most important.
The Study Guide (Tutorial letter 102) is available on myUnisa under Additional Resources.
Please download it from myUnisa. It is also incorporated in the Learning Units, which you
should use to guide your studies week by week.
The software should also be downloaded from myUnisa under Additional Resources for
COS1512, at once if you do not receive Disk2019 immediately after registration. Please note
that it is not necessary to download the full contents of the CD. You need Code::Blocks only.
You may copy it onto a memory stick and install it from there according to the instructions given
on the COS1512 website.
When you want to use myUnisa for the first time, you have to register. Go to my.unisa.ac.za and
click on “Join myUnisa”. Then follow the instructions on the screen. You will get a password for
future use. We also suggest that you get your myLife email address as soon as possible. See
the Study @ Unisa brochure for instructions. The University communicates with you via this
email address. You also get notified about important announcements for COS1512 via this
email address. Please check your myLife email regularly.
5.3 Additional Resources on myUnisa
Apart from the Disk2019 content that is available on myUnisa under Additional Resources, you
will find other resources such as old exam papers, extra examples of some programming
constructs, etc.
5.4 Announcements on myUnisa
We urge you to access myUnisa on a regular basis. We put announcements on myUnisa
regarding the module on a regular basis.
5.5 Installation of the software
Once you have access to a computer, you should install the software for this module on the
computer. (If you will be using one of Unisa's computer laboratories, the software will already be
installed). The software that you need for COS1512, namely a compiler and an IDE, are
included on the CD-ROM disk that you should have received as part of your study package
(Disk2019). The Learning Units contains full instructions on how to install the compiler and IDE
and how to start using them.
6 STUDY PLAN
Use your Study @ Unisa brochure for general time management and planning skills.
6.1 Syllabus
In this module we cover the following chapters of Savitch:
12
COS1512/101/3/2019
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
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.
6.2 Planning your academic year
In overview, the undergraduate academic year is as follows:
21 January 2019 Academic year begins 8 July 2019 Academic year begins
18 February 2019 First assignment due 5 August 2019 First assignment due
1 April 2019 Second assignment due 16 September 2019 Second assignment due
May/June 2019 Examinations October/November 2019 Examinations
13
Arrange for access to a computer.
We provide two study programmes, one for students who registered for the first semester, and
one for students who registered for the second semester. We recommend that you use the
study programmes as a starting point. You will probably need to adapt this schedule, taking into
account your other modules and your personal circumstances.
Study programme for first semester registration:
14
COS1512/101/3/2019
Read the corresponding discussion given in the Learning Unit for the week when you
have to study the chapter. This discussion is also available in the Study Guide that can
be downloaded from the COS1512 website on myUnisa under Additional resources.
Scan the chapter in Savitch to get an overview of what the chapter is about.
Read the chapter again, making sure that you process the information. Relate the text to
the given program listings. You will sometimes have to read a little ahead or read a whole
section to make meaningful sense of a program listing or discussion. Many students
merely read the code and not the accompanying text that explains the code.
Remember to highlight or indicate all the words or phrases you think are key points the
writer is making. You can use these and the headings to make your concept maps or
summaries whichever you prefer.
Take the source listing of the sample programs in the textbook, type it into a text file,
compile it and execute it. Observe the output produced. Some of the source listings of
the examples can be found on the companion website that goes with your textbook.
Appendix B contains instructions on how to gain access to the source listings. The
Learning Units also contain links to some of the source listings.
15
Do as many as possible of the self-check questions on a section as you study it. Answers
to the self-check questions are available at the end of each chapter.
Answer the assignment questions on the chapter. Implement all programming questions
on your computer.
It is important to realise that the process of learning how to program follows a learning curve:
The more programs you write, the more proficient you will become. Remember that 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 semester to
develop the necessary programming skills. Plan to spend at least 8 hours per week on this
module.
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 and Learning Units 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 and Learning
Units contain 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. We suggest that
you do the assignment question(s) on a specific chapter as soon as you have studied it. This
will allow you to master the study material and to start timeously with your assignments.
The time constraints under the semester system do not allow us to accept late assignments.
16
COS1512/101/3/2019
All the assignments require practical work, i.e. programs that you have to implement on your
computer. Submit the source code 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.
You are required to submit your assignments electronically via myUnisa in PDF format. Please
submit only one PDF file for an assignment. This PDF file should contain the source code as
well as the input and the output produced by that source code for each question in the
assignment. Tutorial Letter 103 under Additional Resources on the COS1512 website on
myUnisa shows you how to create your assignment as a PDF file so that you can submit it
electronically. There is also a video on how to create a PDF file for an assignment under
Additional Resources on the COS1512 website.
For detailed information on how to submit assignments electronically, refer to the Study @
Unisa brochure, which you received with your study package. Instructions on how to register to
become a myUnisa user, are provided on the web site.
You will receive tutorial letters (201 and 202) discussing each assignment. The solution to
assignment 3 is provided on the course website under Additional Resources. 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. In that
case, the mark allocation for the assignment will be adapted. However, as mentioned before,
we discuss each assignment question in a detailed tutorial letter that you will receive after the
due date.
17
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.
You are welcome to work in small groups. However, every member of the group must write and
submit his or her own individual assignment. Therefore, 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 semester mark calculation: Your mark for this module is made
up of a semester mark (20%) and an examination mark (80%). The final semester mark is
calculated based on your performance in assignments throughout the semester. 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.
The weights allocated to the assignments for COS1512 are summarized as follows:
1 20%
2 80%
3 0% (self-assessment)
To explain how this will work, assume that a student receives 75% for assignment 1, and 80%
for assignment 2. His/her year mark will then be calculated as follows:
Total: 0.79
When the total of 0.79 is converted to 20% of the final mark, it will be 15.8%, thus the student’s
semester mark will be 15.8%. The examination will form the remaining 80% of the final mark for
the module. Note that the semester mark will not form part of the final mark for the
supplementary examination.
18
COS1512/101/3/2019
The following formula will be used to calculate your final semester mark:
Semester mark (out of 100) x 20% + Examination mark (out of 100) x 80%
8.2 General assignment numbers
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 all assignments, and
compare them to the solutions provided.
8.2.1 Unique assignment numbers
Go to myUnisa at https://my.unisa.ac.za/.
Click on the assignment number for the assignment that you want to submit.
9 EXAMINATION
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.
20
COS1512/101/3/2019
11 IN CLOSING
Do not hesitate to contact your lecturer or e-tutor by email if you are experiencing problems with
the content of this tutorial letter or any aspect of the module.
I wish you a fascinating and satisfying journey through the learning material and trust that you
will complete the module successfully.
Enjoy the journey!
COS1512 Team
21
12 APPENDIX A: ASSIGNMENTS FOR COS1512
FIRST SEMESTER ASSIGNMENTS
ASSIGNMENT 1 (FIRST SEMESTER)
WEIGHT: 20%
MARKS: 70
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 with
single line spacing and convert it to a PDF file before you submit it. See Additional
Resources on MyUnisa for instructions on how to create a PDF file.
WE DO NOT ACCEPT ANY MEMORY STICKS OR CDs.
The program should use two overloaded functions, each named calcCharges, to calculate the
total charges for the patient. One of the overloaded functions should accept arguments
(parameters) for the in-patient data, while the other function accepts arguments for the out-
patient information. Both functions should return the total charges.
Test both overloaded functions in your program.
22
COS1512/101/3/2019
Question 2 (5 marks)
Write a C++ program to validate whether a matric student qualify to register for the BSc
Computer Science degree. The student qualifies if he or she is has achieved a minimum of 60%
in Mathematics, Physical Science and English. The program should use the assert function to
validate that the marks of the students are not more than 100%. The program should then
display a message to inform the student whether he qualifies or not. Run your program twice,
once to test it with marks for Mathematics, Physical Science and English less than or equal to
100%; and the second time testing it with one of the marks for Mathematics, Physical Science
and English more than 100%. Submit the output for both runs.
Run your program to calculate the road fines owed by a car with registration number ABC123.
Fines.dat:
ABC123 400
DEC234 340
ABC123 500
GED345 600
ABC123 240
GEE600 120
GED345 230
GEE600 470
ABC123 120
NB: You should not count the number of lines in the file to determine how many times the file
should be accessed.
Sample output:
Please enter registration number: ABC123
Fines:
R400.00
R500.00
R240.00
R120.00
Total fine due R1260.00
23
Question 4 (15 marks)
To make phone numbers easier to remember, some companies use letters to show their phone
numbers. For example, using letters, the telephone number 438 5626 can be shown as GET
LOAN. In some cases, to make numbers more meaningful, companies may use more than
seven letters. For example, 225 5466 can be displayed as CALL HOME, which uses eight
letters.
Write a C++ program that reads a list of telephone numbers expressed in capital letters from a
text file and converts the telephone numbers in capital letters, to the corresponding telephone
numbers in digits. Each converted phone number should be displayed on the console in both
formats, alphabetic and digital. At the same time, the program creates another file in which the
telephone numbers appear in digital format, one number per line. Allow the user to specify the
name of the input file, as well as the name of the output file.
Apply the following convention: If a number consists of more than seven letters, only the first
seven letters are processed. A space is displayed between the third and fourth digits. Letters A,
B and C corresponds to digit 2; letters D, E and F to digit 3; letters G, H and I to digit 4; letters J,
K and L to digit 5; letters M, N and O to digit 6; letters P, Q R and S to digit 7; letters T, U and V
to digit 8; and letters W, X, Y and Z to digit 9. If any other character is encountered, a * is
displayed.
The input file contains the following data, with one number per line:
CALL HOME
GET LOAN
Hi THERE
BYE FOR NOW
HELP ME PASS
For example, once the first number in the input file has been processed, the console window
should display the following:
(c) What is the difference between assignment statements p1 = p2; and *p1 = *p2;
24
COS1512/101/3/2019
i. Define two pointer types p1 and p2 for pointer variables that contain pointers to
int variables.
iv. Dynamically allocate an integer variable and store its address in p2.
vi. Assign the result of b divided by a to the variable that p2 is pointing to.
ix. Assign the value of the variable that p2 is pointing to, to the variable that p3 is
pointing to.
x. Add 6 to variable a.
xi. Assign twice the value of the variable that p3 is pointing to, to the variable that p1
is pointing to
xiii. What is the value of the variable that p1 is pointing to at this stage? (Hint: Add
statements (i) – (xiii) in a C++ program and display the value of the variable in
question).
xiv. Free the memory allocated to the variables that p1, p2 and p3 are pointing to.
i. Declare an int variable count, ask the user to input its value, and read in the
value.
ii. Define a pointer type PtrType for pointer variables that contain pointers to int
variables.
iv. Dynamically allocate an array of count integers and store its address in p1.
v. Initialise the elements of the array that p1 is pointing to, so that each element has
the value of its position in the array (starting at position 0 as the first position).
vi. Display the values of the array elements – each element on a new line.
25
vii. Free the memory allocated to the array that p1 is pointing to.
26
COS1512/101/3/2019
EXTENTION: None
WEIGHT: 80%
MARKS: 110
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 with
single line spacing and convert it to a PDF file before you submit it. See Additional
Resources on MyUnisa for instructions on how to create a PDF file.
WE DO NOT ACCEPT ANY MEMORY STICKS OR CDs.
Question 1 (5 marks)
Consider the following structure used to keep module records:
struct Module
{
string moduleName;
string moduleCode;
string lecturer;
int nrStudents;
}
Turn the module record into a class type rather than a structure type. The module 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 module‘s name and lecturer to a blank string, the
module code to seven 0’s and the number of students to 0;
an overloaded constructor that sets the member variables to specified values;
27
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 program should input a value for each of the
member variables, use the overloaded constructor to instantiate a module object and then print
all the available information for that module. Use the keyboard to supply input and display the
output on the screen. Test your program with the following input:
Module name: Introduction to Programming II
Module code: COS1512
Lecturer: Dr Schoeman
Number of students: 534
(a) What is the purpose of the keywords public and private in the class declaration?
28
COS1512/101/3/2019
Question 3 (5 marks)
Consider the class declaration and main() function below. There are two errors in the main()
function. Name the errors and explain how to fix them.
class Game
{
public:
Game();
string getName();
int getLevel();
double getScore();
private:
string Name;
string Champion;
int Level
double Score;
};
int main()
{
Game sodoku, brickbreaker[2];
.........(additional code)
.........(additional code)
return 0;
cout << "The first brickbreaker player is "
<< brickbreaker.getName() << endl;
}
The questions below refer to the class declaration of the class Money, which represents the
South African currency. The class has two integer data members, rands and cents.
#include <iostream>
using namespace std;
class Money
{
public:
Money(); // default constructor
Money(int r, int c); // constructor
~Money(); // destructor
int theRands() const;
int theCents() const;
Money Plus(Money m);
Money operator+ (Money & m);
bool GreaterThan(Money m);
private:
29
int rands;
int cents;
};
int main()
{
Money m1;
Money m2(15,90);
Money m3(5,15);
m1 = m2.Plus(m3);
cout << m1 << " + " << m2 << " gives " << m1.Plus(m2) << endl;
m1 = m2 + m3;
cout << m2 << " + " << m3 << " gives " << m1 << endl;
if (m2.GreaterThan(m1))
cout << m2 << " is greater than " << m1 << endl;
else
cout << m2 << " is less than " << m1 << endl;
return 0;
}
(a) What is the purpose of the keywords public and private in the class declaration?
(d) Implement the theRands and the theCents member functions. theRands returns the
number of rands and theCents returns the number of cents.
(d) Implement the Plus()member function. The Plus() member function should add a
Money object to the existing Money object, and return the sum as a Money object.
(e) Implement the overloaded operator+ that adds a Money object to the existing Money
object, and returns the sum as a Money object.
(f) The member function greaterThan() is used to compare two Money objects with each
other. Give an implementation for this member function.
(g) Overload the stream insertion operator as a friend function. It should use the member
functions the theRands and the theCents to write the value of the Money object to the
given output stream.
(h) The statement
if (m1 > m2)
cout << m2 << " is greater than " << m1 << endl;
else
cout << m2 << " is less than " << m1 << endl;
displays a message to indicate which value is bigger. Give three different implementations
for the overloaded operator > to accomplish this:
using the member function greaterThan()
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.
30
COS1512/101/3/2019
(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 using "//".
Enrichment exercise:
Turn the Money class 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.
PLEASE NOTE: The enrichment exercises do not form part of the assignment. It is for practice
only.
Question 5 (20 marks)
Define a class MedicalAidMember as an aDT that uses separate compilation, i.e. separate
files for the interface and the implementation. The class represents the medical aid record for a
staff member and has five member variables:
name, a string that holds the combined first name and last name of the staff member
number, an integer that indicates the medical aid number of the staff member
nrDependants, an integer that denotes the number of dependants the staff member
has
dependants, an array to keep a maximum of six string values, representing the
names of the staff member’s dependants, and
contribution, a double value that indicates the staff member’s medical aid
contribution.
Demonstrate the class in an application program (main.cpp) that is used to create medical aid
records for staff members and then insert these records in a file called MedicalAidData.dat.
The program extracts a staff member’s first name and last name from a file called Staff.dat,
then creates a string representing the staff member’s name. It generates a random number to
be used as the medical aid number for the staff member. An object member is then instantiated
to represent the staff member. The number of dependants the staff member has is obtained
from the user and each dependant’s name is entered. This is used to update the object
member. The staff member’s medical aid contribution (based on the number of dependants) is
then calculated and updated. Thereafter the object member is inserted into the file
MedicalAidData.dat.
Using the input file Staff.dat below and the highlighted input given as shown in the console
output below:
Input file Staff.dat:
Peter McConroy
Dumisang Mkhize
Eleanor Esterhuizen
32
COS1512/101/3/2019
Remember that even if you use the same input file, the medical aid number will differ because it
is generated as a random number. Submit copies of the input and output files and the console
window, as well as all the files in the ADT.
Overload the stream extraction operator >> for the class Module in Question 1 to input values
for an object of class Module either from the keyboard or from a file. Also overload the stream
insertion operator << to output the data for a module either on the screen or to a file.
Use separate compilation and write a program that inputs the name of a lecturer. The program
should then find all the modules taught by that lecturer in a file named Modules.dat, and put
those objects into an array. Assume that the file will never contain data for more than 20
modules. Use the array to determine the total number of students taught by the lecturer, as well
as the average number of students per module taught by the lecturer. Display the names of the
modules, the total number of students taught by the lecturer, and the average number of
students per module taught by the lecturer on the screen. Use the overloaded stream extraction
operator >> to extract objects from file Modules.dat. Use the following data for
Modules.dat:
Introduction to Programming I
COS1511
Dr Schoeman
2354
Introduction to Programming I
COS1511
Mrs du Plessis
2534
Introduction to Programming II
COS1512
Dr Schoeman
458
Introduction to Programming II
COS1512
Mrs du Plessis
2698
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.
This is an additional exercise which you can try once you have studied Chapter 8 (C strings and
Vectors) in Sebesta. You do not have to submit it as part of Assignment 2 and we will not mark
it, if you do submit it.
33
Question 7 (15 marks)
Consider the following class:
class Computer
{
public:
Computer();
Computer(int s, int mm, int hm);
void display_specs(ostream & out)const;
int get_speed()const;
int get_mmemory()const;
int get_hmemory()const;
private:
int speed;
int main_memory;
int harddisk_memory;
};
(b) Test class Computer in a driver program that does the following:
speed: 1600
main memory: 4
hard disk: 16
use the accessor functions to display the specifications of the instantiated object on
the console
display the specifications of the instantiated object on the console with the member
function display_specs().
(c) Derive and implement a class Laptop from class Computer. This class has additional
member variables, battery_time and weight. Class Laptop also has an overloaded
constructor and member functions, get_battime() and get_weight()to return
member variables battery_time and weight respectively. The class Laptop should
override function display_specs() in order to display the member variables of Laptop.
Implement the overloaded constructor for the class Laptop by invoking the base class
constructor.
(d) Test class Laptop in a driver program that does the following:
speed: 1333
main memory: 2
hard disk: 8
battery time: 8
weight: 1.25
use the accessor functions to display the specifications of the instantiated object on
the console.
34
COS1512/101/3/2019
WEIGHT: 20%
MARKS: 70
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 with
single line spacing and convert it to a PDF file before you submit it. See Additional
Resources on MyUnisa for instructions on how to create a PDF file.
WE DO NOT ACCEPT ANY MEMORY STICKS OR CDs.
The volume of a box is its width multiplied by its height multiplied by its length.
The volume of a box is r2h, where r is the radius of the cylinder and h is the height of the
cylinder.
Define a global constant PI and set its value to 3.14. Your program should ask the user which
shape’s volume they want to calculate, and get the required information. It should then call the
correct calcVolume function and output the volume to the screen.
35
Question 2 (5 marks)
Write a C++ program to calculate windchill factor. Windchill factor is an index taking into account
the wind speed and the temperature in cold weather to provide a measure of the chilling effect
of wind at a given air temperature. Windchill can be calculated by the formula:
W = 13.12 +0.6215 * t – 11.37 * v0.16 + 0.3965 * t * v0.016
where
v = wind speed in m/sec
t = temperature in degrees Celsius: t <= 10
W = windchill index (in degrees Celsius)
Write and test a function that returns the windchill index. Your code should ensure that the
restriction on the temperature is not violated.
Hint: See Appendix 4 in Savitch for the function double pow (double, double) to raise
the first argument to the power of the second argument. Remember to include the <cmath>
header.
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 lines in the file to
determine how many times the file must be accessed.
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%
36
COS1512/101/3/2019
INF1501 79.60%
INF1511 48.80%
Create a file named essay.txt containing the essay below. Write a program that will read the
file character by character, change the first character of the first word of each sentence to an
uppercase character, and change all the ‘5’ characters to ‘s’. Write the essay character by
character to an output file called correct.txt.
Ask the user to input the name of the input and output file.
(c) What is the difference between the assignment statement p1=p2; and *p1 = *p2;
i. Define a pointer type int_ptr for pointer variables that contain pointers to int
variables.
37
ii. Declare p1 to be a pointer to an int.
iii. Dynamically allocate an integer variable and store its address in p1.
vii. Free the memory allocated to the variable that p1 is pointing to.
i. Define a pointer type int_ptr for pointer variables that contain pointers to int
variables.
iii. Obtain an integer value nrElements from the user indicating the number of
elements to allocate.
iv. Dynamically allocate an array of nrElements integers and store its address in
p2.
vi. Assume p2 has been initialized and copy the elements of p2 one by one to the
corresponding elements in a.
vii. Free the memory allocated to the variable that p2 is pointing to.
(n) Write a program that asks a user to enter the size of a dynamic array that stores exam
marks obtained by students. Create the dynamic array and a loop that allows the user to
enter an exam mark into each array element. Loop through the array to calculate the
highest mark obtained and output it. Delete the memory allocated to your dynamic array
before exiting your program.
38
COS1512/101/3/2019
WEIGHT: 80%
MARKS: 110
EXTENTION: 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 with
single line spacing and convert it to a PDF file before you submit it. See Additional
Resources on MyUnisa for instructions on how to create a PDF file.
WE DO NOT ACCEPT ANY MEMORY STICKS OR CDs.
Question 1 (5 marks)
Consider the following structure used to keep an address:
struct Address
{
string streetName;
int streetNr;
string city;
string postalCode;
}
Turn the address record into a class type rather than a structure type. The address record class
should have private member variables for all the data. Include public member functions
for each of the following:
39
a default constructor that initialises the street name and the city to a blank string, the
street number to 0 and the postal code to a string of four 0’s;
member functions to set each of the member variables to a value given as an argument
to the function (i.e. mutators);
and member functions to retrieve the data from each of the member variables (i.e.
accessors).
Use this class in a program which prints an address. The program should input a value for each
of the member variables and then print an address consisting of the values for the member
variables in proper address format. Use the keyboard to supply input and display the output on
the screen. Test your program with the following input:
Street name: Preller St
Street number: 543
City: Muckleneuk
Postal code: 0002
(a) What is the purpose of the keywords public and private in the class declaration?
40
COS1512/101/3/2019
Question 3 (5 marks)
Consider the following class declaration with a main() function. There are two errors in the
main() function. Name them and explain how to fix them.
class Restaurant
{
public:
Restaurant();
int getTables();
int getTempStaff();
int getPermStaff();
string getShifts();
private:
string Menu;
int Tables;
int TempStaff;
int PermStaff;
string Shifts[3];
};
int main()
{
Restaurant mimmos;
.........(additional code)
string menu = mimmos.Menu;
.........(additional code)
//Retrieve word
string Scrabble:: GetWord()
{
return(wordBuilt);
}
//Retrieve points
int Scrabble:: GetPoints()
{
return(points);
}
int main(){
int point;
string word;
string let1, let2, let3;
int rest;
Scrabble Scrabble1;
Scrabble1.SetLetters();
Scrabble1.GetLetters(let1, let2, let3);
cout << "\nLet's play a bit of scrabble...You get 3 tries..."
<< endl;
cout << "Please make the longest word possible using the "
<< "following letters:\n" << let1 << endl;
cout << "\nYou will be penalised for letters not used.\n";
cin >> word;
rest = 10 - word.size();
Scrabble1.SetWord(word,rest);
Scrabble1.Calculate();
Scrabble1.Penalize();
cout << Scrabble1 << endl;
cout << "\nPlease make the longest word possible using the "
<< "following letters:\n"<<let2<<endl;
cout << "\nYou will be penalised for letters not used.\n";
cin >> word;
rest = 10 - word.size();
Scrabble1.SetWord(word,rest);
42
COS1512/101/3/2019
Scrabble1.Calculate();
Scrabble1.Penalize();
cout << Scrabble1 << endl;
cout << "\nPlease make the longest word possible using the "
<< "following letters:\n"<<let3<<endl;
cout << "\nYou will be penalised for letters not used.\n";
cin >> word;
rest = 10 - word.size();
Scrabble1.SetWord(word,rest);
Scrabble1.Calculate();
Scrabble1.Penalize();
cout << Scrabble1 << endl;
return(0);
}
The program displays a number of letters on the screen and asks the user to build a word, using
as many of the letters as possible.
(a) What is the purpose of the keywords public and private in the class declaration?
(b) What is the purpose of a constructor?
(c) Is SetLetters()an accessor or mutator? Explain your answer.
(d) Complete the implementation of the class by writing code for the following:
Implement a destructor for the class Scrabble.
Implement the constructors. By default wordBuilt should be initialized to
“SCRABBLE” and unused to 10. The second constructor allows the user to initialize
wordBuilt and unused to other values.
Implement the member function GetLetters().
Implement the member function SetWord() which will update the private variable
wordBuilt with the word that the user built as well as update the variable unused
with the number of letters that the user did not use.
Implement the member function Penalize(). This function must deduct three points
for each letter not used, and update points accordingly.
Implement the member function Calculate(). This function must calculate and
update points according to the rules below:
Letters A,E,I,U and O, are worth 4 points each,
43
Overload the insertion operator to send the word and points to the given output
stream.
Enrichment Exercise:
Turn the Scrabble class 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 file that tests the ADT.
PLEASE NOTE: The enrichment exercises do not form part of the assignment. It is for practice
only.
Define a class Shares as an ADT that uses separate compilation (i.e separate interface and
implementation files). The class represents shares for a shareholder in a specific company on
the JSE. This class has four member variables:
company, a string that holds the name of the company
nrShares, an integer value that indicates the number of shares this shareholder owns
unitValue, a float value that indicates the current value of one share and
pastUnitValues, an array to keep five double values.
Demonstrate the class in an application program (main()). This program obtains the detail for
a new purchase of shares from the user and creates an object to represent the new purchase of
shares. It then extracts all existing shares in the user’s portfolio one by one from a file
Portfolio.dat and checks whether the shareholder already has shares in the company. If
the user already holds shares in the company, the member function updateShares() is used
to update the shares in the company to include the new shares purchased. All shares (updated
as well as unchanged existing shares) are output to a new portfolio file called
NewPortfolio.dat. If the user does not already own shares in the company, the new
purchase of shares are simply output to NewPortfolio.dat. Before outputting a shareholding
to NewPortfolio.dat, the program calculates the value of the shareholding (number of
shares * unit value per share) and adds it to a running total. The running total is used to
calculate the total value of the shares, which is displayed on the console window at the end of
the program. Be sure to use appropriate member functions in the required statements. See
below for sample input and corresponding output. Submit copies of the input and output files
and the console window, as well as all the files in the ADT.
Portfolio.dat
OldMutual 10 12.5 0 0 0 0 12.5
Sanlam 15 10.5 12.43 15.3 11.4 9.4 10.5
Allied 5 6.5 0 0 8.45 7.98 6.5
Output:
Enter name of company in which shares are bought: OldMutual
Enter number of shares bought: 10
Enter unit value of one share: 5
NewPortfolio.dat
OldMutual 20 5 0 0 0 12.5 5
Sanlam 15 10.5 12.43 15.3 11.4 9.4 10.5
Allied 5 6.5 0 0 8.45 7.98 6.5
Overload the stream extraction operator >> for the class Address defined in question 1 to
input an object of class Address either from the keyboard or from a file. Also overload the
stream insertion operator << to output an Address object either to the screen or to a file.
Use separate compilation to convert class Address to an ADT. Then write an application
program that requests the user to specify a postal code and uses the overloaded extraction
operator >> to extract Address objects one by one from a file named Address.dat.
Compare the postal code supplied by the user to the postal code of each object extracted from
the file. If the postal codes are the same, put the object into an array of Address objects.
Assume that the array will never need to contain more than 20 Address objects. Once all the
45
objects have been extracted from the file and compared to the user-specified postal code, use
the overloaded insertion operator << to display all the Address objects in the array.
If the user input 0181 as the postal code, your program should display the two addresses in
Pretoria on the screen.
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.
This is an additional exercise which you can try once you have studied Chapter 8 (C strings and
Vectors) in Savitch. You do not have to submit it as part of Assignment 2 and we will not mark it,
if you do submit it.
Define a class Employee with member variables for an employee’s basic salary, pension
amount, medical aid amount and tax percentage. (The medical aid amount and pension amount
is what the employee pays – the company also contributes the same amount towards the
employee’s salary). The tax is calculated on the sum of the basic salary, pension amount and
medical aid amount.
Add appropriate constructors and accessors for class Employee and include the following
member functions:
a member function calcTax()to calculate the amount that will be deducted from the
employee’s salary for tax.
46
COS1512/101/3/2019
a member function calcGrossPay() to calculate the gross pay consisting of the basic
salary plus the pension amount (contributed by the company) plus the medical aid
amount (contributed by the company).
(f) Test class Employee in a driver program that does the following:
Instantiates an object of class Employee, with the following details:
basic salary: R25110.00
pension amount: R2350.00
medical aid amount: R2400.00
% tax paid: 0.08.
Use the accessor functions to display the specifications of the instantiated object on
the console.
Calculate and display an employee’s net salary by deducting the tax amount and the
medical aid and pension deductions from the gross salary. Use functions
calcTax(), calcGrossSalary()and calcDeductions()to accomplish this.
(g) Derive and implement a class Manager from class Employee. This class has an
additional member variable, Allowance (the entertainment allowance amount that a
manager receives). Class Manager also has an overloaded constructor and a function
Display() that displays the salary details of a manager. The class Manager should
override function calcTax() in order to include the entertainment allowance in the
taxable amount when the tax percentage is calculated. It should also override function
calcGrossPay()to include the entertainment allowance.
Implement the overloaded constructor for the class Manager by invoking the base class
constructor.
(h) Test class Manager in a driver program that does the following:
instantiates an object of class Manager, with the following details:
basic salary: R60560.00
pension amount: R5500.00
medical aid amount: R2800.00
allowance: R3100.00
% tax paid: 0.14.
display the specifications of the instantiated object on the console with the member
function Display()
Calculate and display a manager’s net salary by deducting the tax amount and the
medical aid and pension deductions from the gross salary. Use functions
calcTax(), calcGrossSalary()and calcDeductions()to accomplish this.
47
SELF ASSESSMENT ASSIGNMENT 3 (SEMESTER 1 AND SEMESTER 2)
WEIGHT: None
MARKS: 0
This assignment is for self-assessment. Do not submit this assignment. The solution to this
assignment appears in Appendix E of this tutorial letter.
Question 1
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
48
COS1512/101/3/2019
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()
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 2
49
Consider the class definitions below and answer the questions that follow:
class Date
{
public:
friend ostream & operator<<(ostream & cout, const Date & d);
Date(int y, int m, int d);
private:
int year, month, day;
};
class Publication
{
public:
Publication(const string & p, const Date & d,
const string & t);
Date GetDate( ) const;
string GetPublisher( )const;
string GetTitle() const;
private:
string publisher;
Date date;
string title;
};
(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 return 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;
};
publisher: FisherKing
date: 01/01/2000
title: Global Warming
isbn : 123456789
author: Ann Miller
(v) Write a statement to overload operator<< as a friend function to the class Book
and add the following implementation to your code:
ostream & operator<<(ostream & out, const Book & B)
{
out<<B.title<<endl;
out<<B.publisher<<endl;
out<<B.date<<endl;
out<<B.author<<endl;
out<<B.ISBN<<endl;
}
Question 3
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
51
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 4
Write a template version of a search function for determining whether an array contains a
particular value.
Question 5
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;
private:
vector< vector<Object> > array;
int rows;
int cols;
};
52
COS1512/101/3/2019
53
(v) Output all three matrices.
Notes:
In mathematics, a matrix (plural matrices) is a rectangular table of numbers or, more generally,
a table consisting of abstract quantities that can be added and multiplied. For example, a 4 by 3
matrix is represented as:
6 6 6
5 3 2
3 1 2
2 7 9
Two matrices can be added if, and only if, they have the same dimensions. (That is, both
matrices have matching numbers of rows and columns.) We define their sum by constructing a
third matrix whose entries are the sum of the corresponding entries of the original two matrices.
For example:
4 3 4 2 2 1 6 5 5
1 2 3 + 1 3 2 = 2 5 5
2 2 1 3 4 5 5 6 6
Question 6
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 7
(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
54
COS1512/101/3/2019
on entries in the first column, largest to smallest. Adapt the sorting function from (a) as
necessary.
For example, for the input
-12 3 -12 4 1 1 -12 1 -1 1 2 3 4 2 3 -12
Question 8
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.
55
13 APPENDIX B: THE SOFTWARE FOR COS1512
1. Creating a project
Starting a new project
Launch the Project Wizard through File->New->Project. From the pre-configured templates for
various types of projects, select Console application and click Go.
The console application wizard will appear next. Continue through the menus,
selecting C++ when prompted for a language. In the next screen, give the project a name and
type or select a destination folder. As seen below, Code::Blocks will generate the remaining
entries from these two.
56
COS1512/101/3/2019
Finally, the wizard will ask if this project should use the default compiler (normally GCC) and the
two default builds: Debug and Release. All of these settings are fine. Press finish and the
project will be generated. The main window will turn gray, but that is not a problem, the source
file needs only to be opened. In the Projects tab of the Management panel on the left expand
the folders and double click on the source file main.cpp to open it in the editor.
57
Adding a file to your project
To add the new file to the project, bring up the file template wizard through either File->New-
>File... or Main Toolbar->New file (button)->File...
Select C/C++ source and click Go. Continue through the menus, same as what you have done
before. The last menu will present you with several options. Enter the new filename and location
(as noted, the full path is required). You can browse for the file by clicking the browse button
(see below) to display the file browser window to save the file's location. Checking Add file to
active project will store the filename in the Sources folder of the Projects tab of
the Management panel. Checking any of the build targets will alert Code::Blocks that the file
should be compiled and linked into the selected target(s). click Finish to generate the file.
Browse button
58
COS1512/101/3/2019
The newly created file should open automatically; if it does not, open it by double clicking on its
file in the Projects tab of the Management panel. You can now add code to the new file. Be
careful not to save your files with .c extension (this is not a C++ extension).
Copy an existing file to your project folder or launch a plain text editor (for example Notepad),
and add the following code.
Interface.h
1. #ifndef INTERFACE_H_INCLUDED
2. #define INTERFACE_H_INCLUDED
3.
4. void hello();
5.
6. #endif // INTERFACE_H_INCLUDED
Save this file as a header (Interface.h) in the same directory as the other source files in this
project. Back in Code::Blocks, click Project->Add files... to open a file browser. Here you may
select one or multiple files (using combinations of Ctrl and Shift). (The option Project->Add files
recursively... will search through all the subdirectories in the given folder, selecting the relevant
files for inclusion.) Select Interface.h, and click Open to bring up a dialog requesting to which
build targets the file(s) should belong. For this example, select both targets.
59
Note: if the current project has only one build target, this dialog will be skipped.
Returning to the main source (main.cpp) include the header file and replace the cout function
to match the new setup of the project.
main.cpp
1. #include "Interface.h"
2.
3. int main()
4. {
5. hello();
6. return0;
7. }
Press Ctrl-F9 or File->Build, orCompiler Toolbar->Build (button - the gear) to compile the
project. If the following output is generated in the build log (in the bottom panel) then all steps
were followed correctly.
-------------- Build: Debug in MyFirst Project ---------------
Compiling: main.cpp
Linking console executable: bin\Debug\MyFirst Project.exe
Output size is 913.10 KB
Process terminated with status 0 (0 minutes, 1 seconds)
0 errors, 0 warnings
You can now “run” the project by either clicking the Run button or hitting Ctrl-F10.
Note: the option F9 (for build and run) combines these commands, and may be more useful in
some situations.
Removing a file
You can remove a file by simply right-clicking on the file name in the Projects tab of the
Management panel and selecting Remove file from project.
60
COS1512/101/3/2019
Note: removing a file from a project does not physically delete it.
2. Printing
To print a C++ program, choose the "Print" option on the "File" menu of Code::Blocks. (If you
are submitting an assignment via myUnisa, you don't need to print. 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 I/O window after running your program, you can copy the text to a
word processor (an editor). The steps involved are as follows:
Position the mouse over the console window (the output window). Right-click, and
choose Mark from the drop-down menu.
Hold the Shift key down and use the arrow keys to mark (highlight) the text as a block.
Press the Enter key to copy the highlighted text to the clipboard.
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:
Run your program, and when it has finished executing (and you are happy with the
output) close the console window.
Open a separate DOS window (or Command window) and change the directory to where
your program is. (You'll need to type something like cd \unisa\cos1512.)
61
Test whether your program is actually in the current directory by typing its name at the
DOS prompt, eg. first.exe followed by <Enter>. If you get the message "Bad command
or filename" you are either in the wrong directory or the name of the executable file is
incorrect. You must be able to run the program from the DOS prompt before proceeding.
Make sure that your printer is switched on, is "On-line" and has paper in it, etc.
Press <Ctrl+P> to ensure that all the output generated from now on is sent to the printer.
Type the name of the executable file, eg. first.exe and press <Enter> to run your
program again.
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.
15 APPENDIX D: GLOSSARY
The following link provides a glossary for English/Afrikaans IT terminology:
http://www.coetzee.org/woordelys/
62
COS1512/101/3/2019
Answer the following questions based on the code fragment given above:
(a) Is line 18 a valid access? Justify your answer?
Yes.
The variable x is a private data member of the class A and therefore it can only be
accessed by other member functions and operators of the class A. getX() is a member
function of class A and therefore line 18 is a valid access.
(d) 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()
(a) 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.
64
COS1512/101/3/2019
With protected inheritance, public and protected members of the base class
become protected members of the derived class.
Private data members or member functions resulting from the inheritance: None
Protected data members or member functions resulting from the inheritance: setX()
and getX()
Public data members or member functions resulting from the inheritance: None
Discussion:
When deriving a class from a public base class, public members of the base class become
public members of the derived class and protected members of the base class become
protected members of the derived class. A base class’ private members are never directly
accessible from a derived class, but can be accessed through calls to the public and
protected members of the base class.
When deriving from a protected base class, public and protected members of the base
class become protected members of the derived class. When deriving from a private base
class, public and protected members of the base class become private members of the
derived class. Private and protected inheritance are not “is-a” relationships [Reference:
Study Guide (Tutorial Letter 102 available under Additional Resources on the COS1512 website
on myUnisa ), chapter 15].
Question 2
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;
65
};
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"
66
COS1512/101/3/2019
#include "Date.h"
#include <string>
};
#endif
string Book::getAuthor()const
{
return author;
}
(d) Recode the following interface such that class Magazine, derives from class
Publication:
#ifndef MAGAZINE_H
#define MAGAZINE_H
#include "Publication.h"
67
class Magazine: public Publication
{
public:
Magazine(const string & p, const Date & d, const string & t,
int ipy);
int GetIssuesPerYear( ) const;
private:
int issuesPerYear;
};
#endif
(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;
68
COS1512/101/3/2019
(g) Write a statement to overload operator<< as a friend function to the class Book and
insert the following implementation to your code:
ostream & operator<<(ostream & out, const Book & B)
{
out<<B.title<<endl;
out<<B.publisher<<endl;
out<<B.date<<endl;
out<<B.author<<endl;
out<<B.ISBN<<endl;
}
70
COS1512/101/3/2019
#endif
71
#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>
#endif
72
COS1512/101/3/2019
Filename: Book.cpp
#include "Book.h"
#include <string>
using namespace std;
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;
};
#endif
Filename: Magazine.cpp
#include "Magazine.h"
Filename: Test.cpp
#include <iostream>
#include "Date.h"
#include "Publication.h"
#include "Book.h"
#include "Magazine.h"
return 0;
}
Question 3
Discussion:
For this question, you had to define a function template that searches an array for a specific
value and returns the index of the first occurrence of that value. The template should have
parameters for a partially filled array and for a value of the base type of the array. If the value is
in the partially filled array, then the function returns the index of the first occurrence of that
value, otherwise the function returns -1. The base type of the array is a type parameter.
Function templates are special functions that can operate with generic types. This allows us to
create a function template whose functionality can be adapted to more than one variable type or
class without repeating the code for each type. For instance, with this program we used the
same search() function for an array of doubles (Doubles), an array of characters
(Characters) and an array of integers (Integers). Without templates we would have had to
write a separate search() function for each type of array. (Section 17.1 of Savitch has
detailed explanations on the declarations of function templates.)
74
COS1512/101/3/2019
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};
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 4
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)
return true;
}
return false;
76
COS1512/101/3/2019
}
//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 5
For this question, you had to implement the operations of a Matrix class template.
template<class Object>
int Matrix<Object>::GetRow() const
{
return rows;
}
template<class Object>
int Matrix<Object>::GetCol() const
{
return cols;
78
COS1512/101/3/2019
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);
79
M2.SetValue(6,0,1);
M2.SetValue(7,1,0);
M2.SetValue(8,1,1);
Matrix<int> M3(2,2);
M3 = M1 + M2;
M1.OutPut(cout); cout<<endl;
M2.OutPut(cout);cout<<endl;
M3.OutPut(cout);cout<<endl;
return 0;
}
Output Produced:
1 2
3 4
5 6
7 8
6 8
10 12
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
80
COS1512/101/3/2019
Question 6
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'.
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);
//create new string with first and last name in pig latin
strcpy(newName, first);
strcat(newName, " "); //add space between first and last name
81
strcat(newName, last);
cout << "Dear " << copyFirst << " " << copyLast
<< " in pig latin your name is " << newName << endl;
return 0;
}
Question 7
7. (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:
82
COS1512/101/3/2019
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.
7. (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:
83
void read_vector(vector<int>& v, istream& in_stream);
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>
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);
}
//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;
86
COS1512/101/3/2019
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
87
2
3
-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 8
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;
88
COS1512/101/3/2019
return 0;
}
Output:
The sum between 13 and 17 is:75
The sum between 13 and 13 is:13
The sum between 13 and 14 is:27
Press any key to continue . . .
Discussion:
To solve this question, we need to determine the base case and the general case. The base
case is when the solution can be obtained directly.
The base case:
If m is equal to n then we can immediately determine the sum to be m. For example the sum
between 13 and 13 would be 13.
The general case on the other hand, is a little harder to deduce:
Consider the following example:
sum(13,17) = 13 + 14 + 15 + 16 + 17
Recursively:
sum(m,n) = m + sum(m+1,n)
89
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,
sum(13,17) sum(13,17) = 75
since m!=n
return 13 + 62 = 75
step a return 13 + sum (14,17);
sum(14,17) = 62
sum(14,17)
since m!=n
return 14 + 48 = 62
step b return 14 + sum (15,17);
sum(15,17) = 48
sum(15,17)
since m != n
return 15 + 33 = 48
step c return 15 + sum(16,17)
sum(16,17) = 33
sum(16,17)
sum(17,17)
since m = n return 17
step e
return 17
So eventually the recursive calls will stop at sum(17,17) - because an answer of 17 can be
returned.
So sum(15,17) is:
So sum(14,17) is:
90
COS1512/101/3/2019
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.
©
Unisa 2019
91