You are on page 1of 107

COS111U/101/3/2009

Introduction to programming 1 Tutorial letter 101 for COS111U General information, study schedule and assignments
COS111U is a semester module. You need AT LEAST eight hours per week for this module. If you do not receive your study material immediately after registration, you have to download it from the Internet so that you are able to start IMMEDIATELY with your studies. The Study Guide and the software in particular are essential. See Section 3 of this tutorial letter for detail about the downloading of study material. To gain admission to the examination you have to submit Assignment 1 in time. The due date is 27 February if you are registered for the first semester and 21 August if you are registered for the second semester.

School of Computing

This letter (COS111U/101/3/2009) and Tutorial Letter COSALLF/301/4/2009 contain important information that you are going to need during the year. Please read them carefully. Another publication which can be of real help is the brochure Services and Procedures which you received with your tutorial matter. It contains information about computer laboratories, the library, myUnisa, assistance with study skills, et cetera. It also contains telephone numbers of several Unisa departments, for example Examinations, Assignments, Despatch, Finances and Student Administration. 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 this brochure. The School should only be contacted about academic matters. If you cannot find the telephone number of the specific department in the brochure, please use the contact information below: Telephone - RSA: 0861 670 411 International calls: +27 11 670 9000 Fax number: 012 429 4150 / +27 12 429 4150 E-mail: study-info@unisa.ac.za The Department of Despatch (+27 12 429 4104) should supply you with the following tutorial matter for this module: tutorial letters study guide CD. When you register, you will receive an inventory letter containing information about your tutorial matter. See also the booklet Services and procedures. Please read Section 3 of this tutorial letter if you do not immediately receive the Study Guide or the CD, because you should download it from the Internet in that case.

COS111U/101/3/2009

CONTENTS Section 1 Introduction Section 2 Tutorial matter 2.1 Study Guide 2.2 Errata in the Study Guide 2.3 Software 2.4 Tutorial letters 2.5 Additional reading Section 3 The downloading of study material Section 4 Practical work Section 5 Student support Section 6 The Internet Section 7 The syllabus Section 8 Recommended study programme 8.1 Starting COS111U 8.2 Installing the software 8.3 Working through the Study Guide Section 9 Examination admission Section 10 Doing the assignments General information Semester mark Section 11 The assignments of semester 1 Assignment 1 Assignment 2 Assignment 3 Section 12 The assignments of semester 2 Assignment 1 Assignment 2 Assignment 3 Appendix 1 Installing and using the software Appendix 2 Vista Appendix 3 Buying a computer system Appendix 4 Science Foundation Programme

Section 1

INTRODUCTION

Welcome to COS111U. We hope that you will find it interesting and stimulating and that you will learn a lot about programming. You may send e-mail to the module e-mail address, namely cos111@osprey.unisa.ac.za for any academic queries regarding COS111U. You will shortly receive a tutorial letter where the names and contact details of your COS111U lecturers are supplied. In the mean time, if you would like to speak to a lecturer, you may contact the secretary of the School of Computing at 012 429 6122. This is for academic issues only. (See page 2 for information regarding other kinds of queries.) There are a number of first-year Computer Science and Information Systems modules at Unisa. Here are some of the modules: COS111U deals with the basic concepts of programming and the design of algorithms, using the programming language C++. COS112V is a further introductory course in C++ programming where object-oriented programming is introduced. COS111U is a prerequisite for this module. COS113W provides a general background to computer systems, INF1511 is an introduction to visual programming, and COS101S introduces the mathematics relevant to Computer Science. All the above modules are semester modules and you will need at least 8 hours per week for each, especially for the programming modules. Programming is extremely time-consuming and we do not recommend you to enrol for more than one programming module simultaneously. We begin this tutorial letter by giving you some general background information about COS111U. We discuss the tutorial matter, the syllabus, the study programme, examination admission requirements, semester mark and how to set about submitting assignments. We then give Assignments 1, 2 and 3, first for the first semester and then for the second semester. We end with four appendices, namely instructions for the installation of the software, the Vista operating system, specifications for a suitable computer, and information about the Science Foundation Programme. Some facts about the three assignments: The submission of Assignment 1 determines examination admission. Assignment 2 counts 70% of your semester mark. Assignment 3 is a self-assessment assignment and should not be submitted. Note, however, that it covers important study material.

COS111U/101/3/2009

Section 2

TUTORIAL MATTER

There is NO prescribed book for this module.

Section 2.1

STUDY GUIDE

The Study Guide is written in such a way that it guides you through practical activities that you can work out on the computer or sometimes on paper, so that you can experience what programming is actually like. The Study Guide is in a flexible format. Students who have little previous knowledge of computers will find it very useful to go through all the activities and subactivities in the Study Guide. Those of you who have more computer experience will find that the Study Guide gives guidance on which parts you should do and which parts you may skip. It is important to start with this module immediately after registration. If you do not receive your Study Guide immediately, you should download it from myUnisa or osprey. See Section 3 of this tutorial letter. Lesson 30 of the Study Guide is not examination material but for enrichment. It will also be of help in the transition from COS111U (Introduction to programming 1) to COS112V (Introduction to programming 2).

Section 2.2

ERRATA IN THE STUDY GUIDE

Please let us know if you find any errors in the Study Guide.

Section 2.3

SOFTWARE

The prescribed software for this module is a C++ compiler. Your tuition fees include the C++ compiler. You should have received a CD-Rom disk (Disk 2009) with your study package. This CD contains all the software you will need for the module. In Section 8 of this tutorial letter and on the CD itself, we explain how to install and use the software. To help you, the information is also given in Appendix 1 of this tutorial letter. If you do not receive Disk 2009 upon registration, you should download the software immediately from the Internet so that you are able to start with your studies at once. See Section 3 of this tutorial letter. The lecturers will answer queries about the installation of the software only until 31 January (first semester) and 25 July (second semester). From 1 February and 26 July, respectively, no such problems will be discussed.

Section 2.4

TUTORIAL LETTERS

In addition to the Study Guide, the compiler and this letter, you will receive other tutorial letters during the course of the year. Some will provide additional information (Tutorial Letters 102, 103, etc.) whilst others will discuss Assignments 1, 2 and 3 (Tutorial Letters 201, 202 and 203). It is not necessary to wait for the printed copies of these letters. The tutorial letters will be available on the Internet. Keep an eye upon myUnisa and osprey (the web page of our School). See Section 3 of this tutorial letter.

Section 2.5

ADDITIONAL READING

You do not have to consult any textbooks. However, those of you who want to read further may consider any of the books listed below. (They are not necessarily available in the Unisa library.) James P. Cohoon and Jack W. Davidson. C++ Program Design: An Introduction to Programming and ObjectOriented Design, 3rd edition. London: McGraw-Hill, 2002. HM Deitel and PJ Deitel. C++ How to Program, 2nd edition. Prentice Hall, 1997. John R Hubbard. Schaums Outlines: Programming with C++, 2nd edition. McGraw-Hill, 1996. Walter Savitch. Problem solving with C++, 7th edition. Addison Wesley, 2009. (This book is prescribed for COS112V in 2009.)

Section 3

THE DOWNLOADING OF STUDY MATERIAL

One of the requirements for study at the School of Computing it to have regular access to myUnisa. It is therefore expected from you to download any study material from the Internet that, for whatever reason, is not available on paper in time. You may download it either from myUnisa or from osprey (see below). The study material is updated regularly, thus you need to check the web site at least once a week. Because COS111U 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 is available in separate sections on osprey. If you do not receive a study guide immediately after registration, you should download Section 1 (and later Section 2, et cetera if you still did not receive a hard copy). The software should also be downloaded at once if you do not receive Disk 2009 immediately after registration. Please note that it is not necessary to download the full contents of the CD. You need MinGW and Dev-C++ only. You may copy it onto a memory stick and install it from there according to the instructions given in Appendix 1 of this tutorial letter. myUnisa: When you want to use this facility 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. osprey: Go to osprey.unisa.ac.za and click on Registered students. Then personalise the page. Now you will be able to reach the download section. You will need the login MYDOWNLOAD and the password SOC2009. Note the upper case letters.

Section 4

PRACTICAL WORK

All students must have access to a computer in order to do COS111U successfully. A description of the requirements for the computer appears in Appendix 3 at the end of this tutorial letter.

COS111U/101/3/2009

It is necessary to do extensive practical work on a computer when you study this module. The Study Guide is compiled in such a way that you have to continually design computer programs and get them to work. In addition, in many assignment questions you need to submit printouts of your programs and the results (or electronic copies of these that are combined into one file and submitted through myUnisa). In Appendix 1 (point 4) of this tutorial letter we explain how you can get these printouts. The examination, on the other hand, is a purely written examination and does not involve doing any work on the computer. There are no compulsory practical sessions that students need to attend during the year. The Unisa computer laboratories in a number of centres are available to students for the practical work of COS111U. Please contact your nearest regional office about this. Contact information about the regional offices can be found in the Unisa booklet Services and Procedures.

Section 5

STUDENT SUPPORT

As mentioned in Tutorial Letter COSALLF/301/4/2009, students may make appointments to see a lecturer or may contact lecturers by mail, e-mail or telephone. The e-mail address that you should use, is cos111@osprey.unisa.ac.za You will shortly receive a tutorial letter where the names and contact details of your COS111U lecturers are supplied. In the mean time, if you would like to speak to a lecturer, you may contact the secretary of the School of Computing at 012 429 6122. This is for academic issues only. (See page 2 for information regarding other kinds of queries.) Furthermore, the Student Services Bureau of Unisa provides support for students in general academic matters, such as selecting appropriate modules, developing study skills, adapting to distance education or general difficulties with studies. See COSALLF/301/4/2009, Services and Procedures and page 2 of this tutorial letter for contact information. In addition to this, a number of tutors will be appointed for COS111U. Classes will be given at regular intervals in a number of centres. Contact your nearest regional office for more information about this. (Information about the regional offices can be found in the Unisa booklet Services and Procedures.) This module is furthermore part of the Science Foundation Programme - look at Appendix 4 where information about this is given. You may also organise your own study group. Contact 0861 670 411 to get information about fellow students near you.

Section 6

THE INTERNET

As you know, Unisa is accessible via the Internet. It is a requirement for study at the School of Computing to have regular access to myUnisa. One of the reasons for this is that you will be able to download study material whenever the printed version is not available in time, for whatever reason. See Section 3 of this tutorial letter, Services and Procedures and Tutorial Letter COSALLF/301/4/2009 for details. You are very welcome to take part in the discussion forums. We, the COS111 lecturers, do not take active part there. Also, remember that, if there are any discrepancies between information on paper and information on the web, you should take that on paper as correct except if explicitly told differently. Please do not use the e-mail address of an individual lecturer, but rather the following for any COS111U queries: cos111@osprey.unisa.ac.za

Section 7

THE SYLLABUS

The purpose of he module is to introduce students to programming and to cover the fundamentals of data and control structures, techniques for problem solving and algorithm design, input and output of data from and to the standard input/output stream. Data types and structures which are covered are floating point, integer, character, string, Boolean, one- and two-dimensional arrays. The C++ decision and iteration structures that are covered include if, while, for, switch, do..while. Furthermore, functions with both reference and value parameters are covered, as well as structs.

Section 8
Section 8.1

RECOMMENDED STUDY PROGRAMME


STARTING COS111U

It is essential to have access to a computer to do this module. If you do not have one at home, you must gain access to one somewhere else, possibly at work, at a friends home, or at one of Unisas computer laboratories. You are expected to do three assignments and to submit the first two. We will send out a tutorial letter discussing each assignment after its closing date. You should compare your solutions with these tutorial letters. Since the work in COS111U is progressive and later sections build on earlier ones, we suggest that you begin studying immediately and that you do all three assignments in their proper sequence. In overview, the undergraduate academic year, divided into two semesters, looks as follows: 19 January 10 May 11 May 6 June 13 July 1 November 2 November 28 November Study - first semester Examination Study - second semester Examination

To get going with your studies, we recommend the following steps: Begin studying COS111U by browsing through Tutorial Letters COS111U/101/3/2009 (this tutorial letter) and COSALLF/301/4/2009. There you will find the necessary information about studying at the School of Computing and studying this specific module. In tutorial letter COS111U/101/3/2009 (this one) information is given about, amongst others, the Study Guide and the computer and software you will need. Every COS111U student must use a computer to do this module. You will also find the assignments and explanations about their due dates in this letter. At the same time, you need to organise access to a computer. In Appendix 3 of this tutorial letter we explain what sort of computer you need to use. You may be able to use a computer at a friend's house, at work, at a school, or at a community centre. You may already own a computer, or you may decide to buy one. You could also use a computer at one of Unisas regional offices see the brochure Services and Procedures for more information. Then the software should be installed on the computer, except if it is available already (for example on the computers at the regional offices).

COS111U/101/3/2009

Section 8.2

INSTALLING 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 COS111U, namely a compiler and an IDE, are included on the CD-Rom disk that you should have received as part of your study package (Disk 2009). This disk also contains full instructions on how to install the compiler and IDE and how to start using them. Insert the CD-Rom into the CD-Rom drive of your computer. The first step is to view the file index.html on the CD-Rom. Choose one of the following three methods to do this: Click on the Start button of Windows 95/98/NT/2000/XP. Click on the Run ... option of the menu that appears. Type d:\index.html in the space provided next to Open:. (If your CD-Rom drive is not d:, type the appropriate letter instead of d:.) Click on OK. OR Load Windows Explorer and navigate to the CD-Rom drive. Double-click on the document index.html. OR Load the browser on your computer (probably Internet Explorer). Type d:\index.html for the Address and press Enter. (If your CD-Rom drive is not d:, type the appropriate letter instead of d:.) If your action is successful, a page will appear on the screen introducing the contents of the CD-Rom. On the page that appears, click on the link for COS111U. (The link is the word COS111U, underlined.) Full instructions for installing and using the software are given. Follow those instructions. These instructions are also given in Appendix 1 of this tutorial letter. If you did not receive Disk 2009 upon registration, you should download the necessary software from the web. See Section 3 of this tutorial letter. Do this immediately. The lecturers will answer queries regarding the installation of the software only until 31 January (first semester) and 25 July (second semester). From 1 February and 26 July, respectively, no such queries will be handled.

Section 8.3

WORKING THROUGH THE STUDY GUIDE

After installing the C++ compiler, start at the Preface and then Lesson 1 of the Study Guide. Each lesson in the Study Guide contains Activities and Subactivities. Because you may not have done programming before, you probably will not be able to do the Activities the first time you try them. Do not worry! Work through the Subactivities. They will lead you step by step to do the Activities. If you did not receive the Study Guide upon registration, you should download Section 1 of the Study Guide from the Internet. See Section 3 of this tutorial letter. Do this immediately. We recommend that you use the following study programme as a starting point. You will probably need to adapt this schedule, taking into account your other modules and your personal circumstances. You are expected to spend AT LEAST 8 hours per week on COS111U.

10

SEMESTER 1

Week

Date (Monday) 19 January 26 January 2 February 9 February 16 February 23 February 2 March 9 March 16 March 23 March 30 March 6 April 13 April 20 April

Activity (Lessons in the Study Guide) Install software, study Lesson 1 Lessons 2, 3 and 4 Lessons 5, 6 and 7 Lessons 8, 9 and 10 Lessons 11, 12 and 13 Do Assignment 1 and submit it. Lessons 14, 15 and 16 Lessons 17, 18 and 19 Lessons 20, 21 and 22 Do Assignment 2 and submit it. Lessons 23 and 24 Lessons 25 and 26 Lessons 27 and 28 Lesson 29 Do Assignment 3. Do not submit it.

Remarks

1 2 3 4 5 6 7 8 9 10 11 12 13 14

Lessons 1 to 7 should be finished by 8 February.

Due date 27 February

Due date 20 March Extension date 29 March

Due date 27 April. Do not submit.

15 27 April 4 May until the examination

Revision Revision. Study all study material, including the solutions to the assignments. Read carefully through the examination tutorial letter.

11

COS111U/101/3/2009

SEMESTER 2

Week

Date (Monday) 13 July 20 July 27 July 3 August 10 August 17 August 24 August 31 August 7 September 14 September 21 September 28 September 5 October 12 October

Activity (Lessons in the Study Guide)

Remarks

1 2 3 4 5 6 7 8 9 10 11 12 13 14

15 19 October 26 October until the examination

Install software, Lessons 1 to 7 should be finished by 2 study Lesson 1 August. Lessons 2, 3 and 4 Lessons 5, 6 and 7 Lessons 8, 9 and 10 Lessons 11, 12 and 13 Do Assignment 1 and submit it. Due date 21 August Lessons 14, 15 and 16 Lessons 17, 18 and 19 Lessons 20, 21 and 22 Due date 11 September Do Assignment 2 and submit it. Extension date 20 September Lessons 23 and 24 Lessons 25 and 26 Lessons 27 and 28 Lesson 29 Do Assignment 3. Do not submit it. Due date 19 October. Do not submit. Revision Revision. Study all study material, including the solutions to the assignments. Read carefully through the examination tutorial letter.

For examination revision, go through the Study Guide and all the tutorial letters. You will also receive an examination tutorial letter telling you about the examination. Remember that COS111U has a large practical component and that it is essential to gain a lot of experience in order to learn to program well. Because of this, you will probably find that you need to work hard and consistently to develop the necessary computer background and programming skills.

12

SECTION 9

EXAMINATION ADMISSION

Make a note of your examination dates and arrange with your employer for leave in good time. The COS111U examination will be in May if you are registered for the first semester or in November if you are registered for the second semester. Check for clashes on the examination time-table and should there be any between your modules, discuss them with the Student Administration department. The COS111U examination is a written examination, i.e. not done on a computer. However, the questions are set in such a way that only students who are able to program will pass the examination. To gain admission to the examination, you have to submit (the multiple choice) Assignment 1 before or on 27 February if you are registered for the first semester, and before or on 21 August if you are registered for the second semester. If you want to submit it electronically and myUnisa is off-line during that time, you need not contact us, because we will be aware of it. Simply submit it as soon as myUnisa is available again.

SECTION 10

DOING THE ASSIGNMENTS

Section 10.1 GENERAL INFORMATION


To do assignments is extremely important when one learns to program. It is only by actually typing in programs, debugging them and getting them to do what is required that one learns how to program. We strongly advise you to do all three assignments. The assignments of the first semester are given in Section 11 of this tutorial letter and those of the second semester in Section 12. The tutorial matter to study for each assignment appears in the study timetables on the two previous pages and at the start of each assignment. Give yourself enough time to do the assignments properly, realising that a single session in front of the computer will not be sufficient at all to complete a programming task. Follow the procedures in this tutorial letter, in Tutorial Letter COSALLF/301/4/2009 and in the brochure Services and Procedures when submitting your assignments. Assignment 1 is a multiple choice assignment and has to be submitted on a mark reading sheet (by post) or electronically through myUnisa. There is no extension of the due date for this assignment. Assignment 2 may be submitted electronically (by using myUnisa). Consult the Unisa publication Services and Procedures and the website itself in this regard. It may also be submitted through normal post. In that case place your assignment inside an assignment cover with all the particulars filled in on the cover. Instructions for completing assignments appear in the Unisa brochure Services and Procedures. The semester system does not allow for late submission of an assignment. However, we give one week automatic extension for Assignment 2. Refer to the information at the top of the assignment. The work that you have to study during the last weeks of the semester is very important and there will be examination questions set on it. However, because of the constraints of the semester system, Assignment 3 is a self-assessment assignment. Thus you should not submit it. We will put the model solution on myUnisa and osprey on the due date. (You will also receive a printed copy.) Compare your effort to it.

13

COS111U/101/3/2009

The programs must be written in C++. You may not use any other high-level language for COS111U. Your programs must follow the programming style used in the Study Guide. In the assignments and the examination, marks are awarded for documentation, programming style, syntax and logic. You must use the input data as specified in the questions and submit your solutions to the questions (including the programs and their output) in one file through myUnisa, or post everything in the same assignment cover. Programs and their output may not be submitted in writing. They should be submitted either electronically through myUnisa (pasting them in a word processor file), or on paper as printouts from the computer. In Appendix 1 of this tutorial letter we explain how printouts can be made. All students will receive a detailed discussion of all three assignments (Tutorial Letters 201, 202 and 203). Carefully compare these discussions with your own answers and make sure that you understand any differences. You will receive a percentage mark for Assignments 1 and 2 if you submit them by the respective deadlines. The marks obtained for these two assignments form the semester mark for this module see Section 10.2 below. Also note that examination admission is dependent on the submission of Assignment 1. It is possible that not all questions of Assignment 2 will be marked. Please note that you will obtain 0% if you do not submit the question(s) that is/are marked. The unmarked questions will be considered to be self-assessment questions. In those cases, compare your effort with the model solution. As mentioned above, we discuss all the questions of every assignment in the relevant tutorial letter that you will receive after every due date and that will be available on the Internet.

Due date of COS111U assignment Assignment number Semester 1 1 (multiple choice) Compulsory for examination admission 2 3 (self assessing) 27 February Semester 2 21 August Weight for semester mark 30%

20 March 27 April

11 September 19 October

70% 0%

You are welcome to work together in small groups. Contact 0861 670 411 to get information about fellow students near you. However, we expect every member of the group to write and submit the programs on his or her own. Thus, discuss the problem, find solutions, etc., in the group, but then do your own programming and submit your own effort. You will learn to program only if you sit down in front of the computer, type in the code, debug the program and get it to work. It is dishonest to submit the work of somebody else as your own and such unethical behaviour does not become our profession. Plagiarism is the act of taking words, ideas and thoughts of others and passing them off as your own. It is a form of theft which involves a number of dishonest academic activities. The Disciplinary Code for Students (2004) is given to all students at registration. You are advised to study the Code, especially Sections 2.1.13 and 2.1.14 (2004:3-4). Kindly read the Universitys Policy on Copyright Infringement and Plagiarism as well.

14

Section 10.2 SEMESTER MARK


The marks that you obtain for Assignments 1 and 2 form the semester mark for COS111U. The semester mark forms 10% of the final mark for the module. The weights of the COS111U assignments are indicated in the table below: Weight 30% 70% 0%

Assignment 1 Assignment 2 Assignment 3

An example follows: Suppose a student gets 60% for Assignment 1 and 45% for Assignment 2. In order to calculate the semester mark, the mark obtained for the specific assignment is multiplied by the weight. This then forms part of the 10% that the semester mark contributes to the final mark. Therefore: Assignment 1 2 TOTAL Marks obtained 60% 45% Weight 30% 70% Contribution to semester mark 60/100 x 30/100 x 10 1.80 45/100 x 70/100 x 10 3.15 4.95

In this example the student has a semester mark of 4.95. The semester mark will not form part of the final mark of a supplementary examination.

15

COS111U/101/3/2009

Section 11

THE ASSIGNMENTS OF THE FIRST SEMESTER ASSIGNMENT 1 FIRST SEMESTER

(MULTIPLE CHOICE) SUBMISSION: On multiple choice form or electronically through myUnisa

Please note that Assignment 1 has to be submitted in order to gain examination admission. It will be to your own advantage to check whether the assignment has been registered on the system after a few days. If you want to submit the assignment electronically and myUnisa is off-line during that time, you need not contact us, because we will be aware of it. Simply submit it as soon as myUnisa is available again.

DUE DATE EXTENSION TUTORIAL MATTER WEIGHT OF CONTRIBUTION TO SEMESTER MARK UNIQUE NUMBER QUESTIONS

27 February NO extension will be granted for Assignment 1. Study Guide, Lessons 1 - 13 30%

168633

45 questions. 5 options each. Choose one option in every question.

IS YOUR SOFTWARE (both the compiler and the IDE) INSTALLED? Read Appendix 1 of this tutorial letter. Look at Troubleshooting under Using the software in file index.html on Disk 2009 or in Appendix 1 of this tutorial letter if your programs do not compile. If your output flashes on the screen and then disappears, you are probably storing the programs incorrectly. The names of the folders where the programs are stored should not contain space characters, for example My Documents is not permissible. Create a folder cos111 directly below c:\unisa and store your programs there. The names of the programs should also not contain any space characters.

PLEASE TURN OVER

16

Hint: In many of these questions you should type in a short C++ program, compile and run it in order to select the correct option.

Question 1 After the file index.html on Disk 2009 has been opened and after the link to COS111U has been clicked, information appears regarding, amongst others, the installation of the software. Which of the following options is correct? 1. 2. 3. 4. 5. Both the compiler and the IDE may be installed by Method 1. Only the compiler needs to be installed by one of the methods. Only the IDE needs to be installed by one of the methods. The compiler has to be installed by Method 1 and the IDE by Method 2. It is unnecessary to install anything.

Question 2 After the software has been installed, certain folders should be investigated. Click on the icon on the desktop for Dev-C++. Then click on Tools, then on Compiler Options, then on Directories. Four folders appear, namely Binaries, Libraries, C Includes and C++ Includes. Which of the following options is correct? 1. 2. 3. 4. Both Binaries and C++ Includes should be empty. If anything occurs there, it should be deleted. Libraries should contain the path c:\unisa\devcpp\lib. If it is not there, you should add it. C Includes should contain the path c:\unisa\devcpp\include. If it is not there, you should add it. All four folders should look exactly as indicated on Disk 2009 below Troubleshooting under Using the software. If it differs from that, you should delete (by highlighting and clicking on Delete) and add (by typing it in the open window at the bottom, click on Add) as necessary. Then click on OK and reboot. 5. It does not really matter what is listed under the four folders. Questions 3, 4, 5 and 6 are based on the following C++ program: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // Program for assignment 1 of 2009. Questions 3 - 6. #include <iostream> using namespace std; int main( ) { const int MAX_NR_TICKETS = 10; CONST float PRICE_ONE_TICKET = 35.00; int nrTickets; float totalAmount; cout << "How many tickets do you want? " cin >> nrTickets;

17

COS111U/101/3/2009

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

if (nrTickets <= MAX_NR_TICKETS) { totalAmount = nrTickets * PRICE_ONE_TICKET; cout << "You owe R" << totalAmount << endl; else { cout << "Unfortunately you may buy " << MAX_NR_TICKETS << " only. "; totalAmount = MAX_NR_TICKETS * PRICE_ONE_TICKET; cout << "If you want to do that, you owe R" << totalAmount << endl; } return 0; }

Question 3 Which of the following options would rectify the syntax error in line 8? 1. 2. 3. 4. 5, Change the statement to CONST FLOAT PRICE_ONE_TICKET Change the statement to const FLOAT PRICE_ONE_TICKET Change the statement to const float PRICE_ONE_TICKET Change the statement to const float PRICE_ONE_TICKET There is no error, so nothing should be done.

= 35.00; = 35.00; = 35.00; == 35;

Question 4 Which of the following options would rectify the syntax error in line 13? 1 2 3 4 5 Change the statement to cout << "Dear customer: " << "How many tickets do you Change the statement to cout >> "How many tickets do you Change the statement to cout << "How many tickets do you Change the statement to cout << "Dear customer: How many There is no error, so nothing should be done.

want? "; want? " want?" tickets? "

18

Question 5 Which of the following options would rectify the syntax error in line 20? 1 Change the statement to // the else part follows: else Change the statement in line 19 to cout << "You owe R" << totalAmount << endl;} Change the statement in line 19 to cout << "You owe R" << totalAmount << endl: } Change the statement in line 20 to else if (nrTickets > MAX_NR_TICKETS) There is no error, so nothing should be done.

2 3 4 5

Question 6 Which of the following options would rectify the syntax error in line 26? 1 2 3 4 5 Change the statement to >> totalAmount >> endl; Change the statement to totalAmount << endl; Change the statement in line 25 to cout << "If you want to do that, you owe R" << Change the statement in line 25 to cout << "If you want to do that, you owe R"; There is no error, so nothing should be done.

Questions 7 and 8 are based on the following: Every evening the IrresistablePancakeShop donates all unsold pancakes to a shelter for 22 street children. The staff want to make sure that each child gets the same number of pancakes as the others. The staff members get the pancakes that are left over, if any. Suppose three variables nrPancakes, nrEachChildGets, en nrStaffGet are declared as int and suppose that a value has already been assigned to nrPancakes (the total number of pancakes that are available). Question 7 Which of the following options is a correct C++ instruction to calculate the number of pancakes each child gets? 1. 2. 3. 4. 5. nrEachChildGets nrEachChildGets nrEachChildGets nrEachChildGets nrEachChildGets = nrPancakes /= 22; = nrPancakes = nrStaffGet = nrStaffGet / 22; % 22; % 22; / 22;

19

COS111U/101/3/2009

Question 8 Which of the following options is a correct C++ instruction to calculate the number of pancakes the staff members get? 1. 2. 3. 4. 5. nrStaffGet nrStaffGet nrStaffGet nrStaffGet nrStaffGet = nrPancakes / 22; /= 22; = nrPancakes % 22; = nrEachChildGets % 22; = nrEachChildGets / 22;

Questions 9, 10, 11, 12 and 13 are based on the following program: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // Program for assignment 1 of 2009. Questions 9 - 13. #include <iostream> using namespace std; int main( ) { int n1, n2, n3, i; n1 = 345; n2 = n1++; n3 = 'C' - 'A'; i = 1; n1 = 111; while (i < 3) { n1 *= 2; n2 = n1 - i * 4; n3 = i * i; i++; } n1 = 44; n2 = --n1; n3 = n1++; return 0; }

20

Question 9 Which of the options below correctly reflects the situation after Line 11 has been executed? Option 1 Line 11 n1 346 n1 346 n1 346 n1 346 n2 346 n2 345 n2 346 n2 345 n3 2 n3 'B' n3 2 n3 2 i ? i 0 i ? i ?

Option 2

Line 11

Option 3

Line 11

Option 4

Line 11

Option 5

Line 11

None of the above options is correct.

Question 10 Which of the options below correctly reflects the situation after Line 18 has been executed the first time? Option 1 Line 18 n1 222 n1 222 n1 224 n1 224 n2 218 n2 884 n2 220 n2 880 n3 1 n3 1 n3 1 n3 1 i 1 i 1 i 1 i 1

Option 2

Line 18

Option 3

Line 18

Option 4

Line 18

Option 5

Line 18

None of the above options is correct.

21

COS111U/101/3/2009

Question 11 Which of the options below correctly reflects the situation after Line 18 has been executed the second time? Option 1 Line 18 n1 444 n1 444 n1 444 n1 444 n2 1768 n2 436 n2 436 n2 436 n3 4 n3 1 n3 4 n3 2 i 2 i 2 i 2 i 2

Option 2

Line 18

Option 3

Line 18

Option 4

Line 18

Option 5

Line 18

None of the above options is correct.

Question 12 Which of the options below correctly reflects the situation after Line 23 has been executed? Option 1 Line 23 n1 43 n1 43 n1 43 n1 44 n2 43 n2 43 n2 44 n2 43 n3 4 n3 4 n3 4 n3 4 i 2 i 3

Option 2

Line 23

Option 3

Line 23

Option 4

Line 23

Option 5

Line 23

None of the above options is correct.

22

Question 13 Which of the options below correctly reflects the situation after Line 24 has been executed? Option 1 Line 24 n1 44 n1 44 n1 44 n1 44 n2 43 n2 43 n2 43 n2 43 n3 44 n3 43 n3 43 n3 44 i 2 i 2 i 3 i 3

Option 2

Line 24

Option 3

Line 24

Option 4

Line 24

Option 5

Line 24

None of the above options is correct.

Question 14 Which option gives the output of the following program? #include <iostream> using namespace std; int main( ) { float a, b; a = 67.898; b = 43.6789; a /= b; cout.setf(ios::fixed); cout.precision(2); cout << a << " and " << b << endl; return 0; } 1. 2. 3. 4. 5. 1.55 and 43.6789 1.55 and 43.68 1.55448 and 1.55448 1.55 and 1.55 None of the above options indicates the correct output.

Questions 15 and 16 are based on the following program: #include <iostream> using namespace std;

23

COS111U/101/3/2009

int main( ) { char c1, c2, c3; cout << "Enter two characters: "; cin >> c1 >> c2; c3 = c1 + c1 - c2; cout << "New character is " << c3 << endl; return 0; } Question 15 Type in the program given above, compile it and then run it with the following input: z f Which of the following options gives the output? 1. 2. 3. 4. 5. New character is c3 New character is z + z - f New character is New character is None of the above options gives the correct output.

Question 16 Run the program given above again but with the following input: # E Which of the following options gives the output? 1. 2. 3. 4. 5. New character is New character is New character is # + # - E New character is c3 None of the above options gives the correct output.

Questions 17 and 18 are based on the following program: #include <iostream> #include <string> using namespace std; int main( ) { string s1, s2, s3;

24

cout << "Provide input, please: " << endl; cin >> s1; cin.get( ); getline(cin, s2, '\n'); cin >> s3; cout << s1 << endl << s2 << endl << s3 << endl; return 0; } Question 17 Type in the above program, compile it and then run it with the following input: I am so pleased to meet you. Enjoy the day with us. Which of the following options gives the correct output? 1. I am so pleased to meet you. Enjoy 2. I am so pleased to meet you. Enjoy the day with us. The computer will wait for you to enter another string. 3. I am so pleased to meet you. Enjoy the day with us. 4. I am so 5. None of the above options indicates the correct output. Question 18 Run the above program again but with the following input: Goodmorning, everyone. I hope you will all have a lovely day. Which of the following options gives the correct output? 1. Goodmorning , everyone. I 2. Goodmorning, everyone. I hope you will all have a lovely day. The computer will wait for you to enter another string. 3. Goodmorning, everyone. I

25

COS111U/101/3/2009

4. Goodmorning, everyone. I hope you will have a lovely day. 5. None of the above options indicates the correct output. Question 19 Suppose the age of a piece of furniture is stored in the int variable age. Which of the following options is a correct C++ instruction to display an applicable message about the age? 1. if (age > 100) cout << "Age greater than 100"; cout << "Age not greater than 100"; 2. if (age > 100) cout << "Age greater than 100"; else; cout << "Age not greater than 100"; 3. if (age > 100) cout << "Age not greater than 100"; else cout << "Age greater than 100"; 4. if (age > 100) { cout << "Age greater than 100"; else cout << "Age not greater than 100"; } 5. None of the above options is correct. Question 20 Suppose we have to divide the value of a float variable totalAmount by the value of an int variable numberTrans if numberTrans is not zero. The result has to be stored in the float variable averageAmount. Which of the following options gives the correct C++ instruction to do this? 1. if (numberTrans == 0) averageAmount = totalAmount / numberTrans; 2. if (numberTrans = 0) averageAmount = totalAmount / numberTrans; 3. if (numberTrans != 0) averageAmount = totalAmount / numberTrans; 4. if (numberTrans != 0) averageAmount == totalAmount / numberTrans; 5. None of the above options is correct.

26

Question 21 Suppose we have to swop the values of two int variables num1 and num2 if num1 > num2. Which of the following options gives the correct C++ instructions to do this? 1. if (num1 > num2) { int temp = num1; num1 = num2; num2 = temp; } 2. if (num1 > num2) int temp = num2; num2 = num1; num1 = temp; 3. if (num1 > num2) { num1 = num2; num2 = num1; } 4. if (num1 > num2) num1 = num2; num2 = num1; 5. None of the above options is correct or more than one of the options is correct. Question 22 Suppose two char variables c1 and c2 are initialised and then input repeatedly in the body of a while loop. The loop has to be executed as long as the values of c1 and c2 are not both equal to A. Which of the options below is a correct condition for the while loop? 1. 2. 3. 4. 5. ((c1 != 'A') && (c2 != 'A')) ((c1 != 'A') || (c2 != 'A')) ((c1 == 'A') && (c2 == 'A')) ((c1 == 'A') || (c2 == 'A')) None of the above options is correct.

Question 23 Suppose two char variables c1 and c2 are initialised and then input repeatedly in the body of a while loop. The loop has to be exited when the value of c1 or c2 is equal to A. Which of the options below is a correct condition for the while loop? 1. 2. 3. 4. 5. ((c1 != 'A') && (c2 != 'A')) ((c1 != 'A') || (c2 != 'A')) ((c1 == 'A') && (c2 == 'A')) ((c1 == 'A') || (c2 == 'A')) None of the above options is correct.

27

COS111U/101/3/2009

Question 24 Suppose two char variables c1 and c2 and an int variable n1 are initialised. Then values are repeatedly assigned to c1, c2 and n1 in the body of a while loop. The loop has to be executed as long as the values of c1 and c2 are not equal and the value of n1 is not 0. Which of the options below is a correct condition for the while loop? 1. 2. 3. 4. 5. (!(c1 == c2) && (n1 == 0)) ((c1 != c2) || (n1 != 0)) ((c1 != c2) && (n1 != 0)) (!(c1 == c2) || (n1 == 0)) None of the above options is correct.

Question 25 The program below deals with bunches of flowers. The number of flowers in each bunch is repeatedly entered, the total number of flowers and the number of bunches are determined and then the average number of flowers in a bunch is calculated. There is, however, a logical error in the program. Which of the options below the program will rectify the error? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 # include <iostream> using namespace std; int main( ) { int nrFlowers, nrBunches, totalFlowers, average; nrBunches = 0; totalFlowers = 0; cout << "Nr of flowers in first bunch (0 to end): "; while (nrFlowers > 0) { nrBunches++; totalFlowers += nrFlowers; cout << "Nr of flowers in next bunch (0 to end)? "; cin >> nrFlowers; } if (nrBunches > 0) { average = totalFlowers / nrBunches; cout << "Average number of flowers in a bunch is " << average << endl; } return 0; }

28

Insert the following statement between lines 10 and 11: cin >> nrFlowers; Change line 14 to: totalFlowers = totalFlowers + nrFlowers; Change line 16 to: cin >> totalFlowers ; Insert the following statement between lines 22 and 23: else cout << "Average = 0" << endl; 5. None of the above options is correct. 1. 2. 3. 4. Question 26 In the program below the number of votes for two candidates, namely Mr A and Mr B, are counted. The program has, however, a logical error. Which of the options below the program will rectify the error? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1. 2. 3. 4. 5. # include <iostream> using namespace std; int main( ) { char vote; int mrA, mrB; mrA = 0; mrB = 0; cout << "First voter: Vote A or B (or Z to end) "; cin >> vote; while (vote != 'Z') { if (vote == 'A') mrA++; else mrB++; cout << "Next voter: Vote A or B (or Z to end) "; } cout << mrA << " votes for Mr A and " << mrB << " votes for Mr B." << endl; return 0; } Insert the following statement at line 8: // initialise Change line 13 to: while (vote == 'Z') Change line 15 to: if (vote = 'A') Insert the following statement between lines 19 and 20: cin >> vote; None of the above options is correct.

Question 27 Suppose the age of a student is stored in the int variable age and the weight in the float variable mass. Suppose further that we want to assign the value true to a bool variable test if the student is younger than 30

29

COS111U/101/3/2009

and weighs between 55kg and 65kg. (The mass may not be equal to 55kg or 65kg.) Which of the options below is a correct assignment statement? 1. 2. 3. 4. 5. test = (age < 30) && (55 < mass < test = (age < 30) || (55 < mass < test == (age < 30) && (55 < mass) test =(age < 30) && (mass > 55kg) None of the above options is correct. 65); 65); && (mass < 65); && (mass < 65kg);

Question 28 Suppose the following statement appears in a C++ program dealing with towns: bool crit = (age >= 200 || popul < 10000 && age > 100); where the variables age (the age of the town) and popul (the number of residents) have already been declared as int. Suppose further that the program contains a while loop starting as follows: while (crit) Which of the options below indicates when the loop will be executed? 1. The loop is executed if the town is 200 years or older or if there are fewer than 10000 residents. The loop will also be executed if the age is between 100 and 200 years. 2. The loop is executed if the town is 200 years or older. The loop is also executed if the age is between 100 and 200 and there are fewer than 10000 residents. 3. The loop is executed if the town is older than 100 years. The loop is also executed if there are fewer than 10000 residents. 4. The loop is executed only if the town is older than 100 years and has fewer than 10000 residents. 5. None of the above options is correct. Questions 29, 30 and 31 are based on the following fragment of a C++ program: string province; char gender; int shoeSize; cout << "Enter province, gender and shoe size: "; cin >> province >> gender >> shoeSize; if (province != "Gauteng") { if (gender == 'M') { if (shoeSize < 8) cout << "Group A" << endl; } else if (province == "Mpumelanga") cout << "Group B" << endl; else cout << "Group C" << endl; } else if (shoeSize >=6) cout << "Group D" << endl;

30

Question 29 Which of the options below indicates the output if the following input is given? Gauteng 1. 2. 3. 4. 5. M 4

Group A Group B Group C Group D There is no output.

Question 30 Which of the options below indicates the output if the following input is given? Mpumelanga 1. 2. 3. 4. 5. Group A Group B Group C Group D There is no output. M 7

Question 31 Which of the options below indicates the output if the following input is given? EasternCape 1. 2. 3. 4. 5. Group A Group B Group C Group D There is no output. F 7

Question 32 Suppose the variables cap (the capacity of the engine) and year (the year when the car was manufactured) have been declared as int and the variable colour (the colour of the car) has been declared as string. Suppose an eccentric client wants to buy either a red car manufactured not earlier than 2004 and with an engine capacity of more than 1600, or a silver car manufactured before 1985. Which of the options below is a correct C++ instruction to indicate these requirements?

31

COS111U/101/3/2009

1. if (colour == "red") if (cap > 1600) if (year >= 2004) cout << "Yes yes" << endl; else if (colour == "silver" && year < 1985) cout << "Yes yes" << endl; 2. if (colour == "red") { if (cap > 1600) if (year >= 2004) cout << "Yes yes" << endl; } else if (colour == "silver" && year < 1985) cout << "Yes yes" << endl; 3. if (colour == "red") if (cap > 1600) { if (year >= 2004) cout << "Yes yes" << endl; } else if (colour == "silver" && year < 1985) cout << "Yes yes" << endl; 4. if (colour == "red" || colour == "silver") if (cap > 1600) if (year >= 2004 || year < 1985) cout << "Yes yes" << endl; 5. None of the options is correct. Questions 33, 34 and 35 are based on the following fragment of a C++ program where we assume that c has been declared as char: switch(c) { case 'A': case 'B': case 'I': case 'O': default: }

cout << cout << break; cout << cout << cout <<

"Apple"; "Berry"; "Ink fish"; break; "Oak tree" << endl; "Choose yourself";

32

Question 33 Which of the options below indicates the output if the value of c is the following? A 1. 2. 3. 4. 5. Apple Berry AppleBerry AppleChoose yourself None of the options gives the correct output.

Question 34 Which of the options below indicates the output if the value of c is the following? C 1. 2. 3. 4. 5. Ink fish Ink fish Oak tree Ink fish Oak tree Choose yourself Choose yourself None of the options gives the correct output.

Question 35 Which of the options below indicates the output if the value of c is the following? O 1. Oak tree 2. Oak treeChoose yourself 3. Oak tree Choose yourself 4. Choose yourself 5. None of the options gives the correct output. Question 36 Suppose the int variable positionOnLog indicates a soccer teams position on a competition log. Suppose further the string variable description has to give the description of the position as follows: If the position is 1 or 2, the description has to be Excellent. If the position is 3, the description has to be Good. If the position is 4 or 5, the description has to be OK. The description of any other position has to be Poor. These assignments are done in a switch statement. Which of the following options gives a correct C++ statement for this?

33

COS111U/101/3/2009

1. switch(positionOnLog) { case 1: description = "Excellent"; case 2: description = "As case 1"; break; case 3: description = "Good"; break; case 4: description = "OK"; case 5: description = "As case 4"; break; default: description = "Poor"; } 2. switch(positionOnLog) { case 1: case 2: description = "Excellent"; break; case 3: description = "Good"; break; case 4: case 5: description = "OK"; break; default: description = "Poor"; } 3. switch(positionOnLog) { case 2: description case 3: description case 5: description case 6: description } 4. switch(positionOnLog) { case 1: case 2: description case 3: description case 4: case 5: description case 6: description } 5. None of the options is correct. Question 37 Which of the options below is not a correct C++ variable name? 1. 2. 3. 4. 5. x1y2z3 MyMoney aBcDeF grade 7b All the options indicate a correct C++ variable name.

= = = =

"Excellent"; break; "Good"; break; "OK"; break; "Poor";

= "Excellent"; break; = "Good"; break; = "OK"; break; = "Poor";

34

Question 38 Which of the options below is a correct C++ variable name? 1. 2. 3. 4. 5. 50SENTS fivtyRAND 44.44 stars and stripes None of the above options is a correct C++ variable name.

Question 39 Which of the options below is not a correct C++ declaration of a constant? 1. 2. 3. 4. 5. const int NUMBER_OF_WICKETS = 5; const bool TEST = false; const float NR_OF_MATCHES; const int NUMBEROFWICKETS = 5; All the options give a correct C++ declaration of a constant.

Question 40 Which of the options below is not a correct C++ instruction? 1. 2. 3. 4. 5. #INCLUDE <iostream>; int n = 99; if (n > 3) n++; else n--; bool halloThere; All the options give a correct C++ instruction.

Questions 41, 42, 43, 44 and 45 are based on the following: The C++ program below is supposed to determine the average shoe size of a group of primary school children. The shoe sizes have to be input until a size of 0 is entered. Then the average size should be calculated and displayed. The number of pupils should also be displayed. Five C++ statements have been omitted from the program. You have to answer questions 41 to 45 in order to complete the program. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <iostream> using namespace std; int main( ) { int shoeSize, nrPupils, average; float total; nrPupils = 0; total = 0; cout << "Enter first shoe size: "; while (shoeSize != 0) { nrPupils++;

35

COS111U/101/3/2009

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

cout << "Enter next shoe size: "; cin >> shoeSize; } { cout << "Average shoe size is " << average << endl; cout << "Number of pupils is " << nrPupils << endl; } else

return 0; }

Question 41 Which of the options below gives a correct C++ instruction for line 11? 1. 2. 3. 4. 5. cin >> shoeSize >> average; cin >> shoeSize >> nrPupils; cin >> shoeSize; cout << "Enter 0 to end" None of the options indicates a correct instruction.

Question 42 Which of the options below gives a correct C++ instruction for line 15? 1. 2. 3. 4. 5. average = shoeSize; total = nrPupils; average += nrPupils; total += shoeSize; None of the options indicates a correct instruction.

Question 43 Which of the options below gives a correct C++ instruction for line 19? 1. 2. 3. 4. 5. if (nrPupils > 0) if (nrPupils > 0); if (nrPupils == 0); average = shoeSize / nrPupils; None of the options indicates a correct instruction.

36

Question 44 Which of the options below gives a correct C++ instruction for line 21? 1. 2. 3. 4. 5. average = shoeSize / nrPupils + 0.5; average = total / nrPupils + 0.5; average = totalShoeSize / nrPupils + 0.5; average = nrPupils / total + 0.5; None of the options indicates a correct instruction.

Question 45 Which of the options below gives a correct C++ instruction for line 26? 1. 2. 3. 4. 5. average = nrPupils / total; cout << "No input" << endl; cout << average << " No pupils" << endl; average = shoeSize / total + 0.5; None of the options indicates a correct instruction.

37

COS111U/101/3/2009

ASSIGNMENT 2

FIRST SEMESTER

SUBMISSION: Printouts or electronically through myUnisa (in one file)


Please note that we automatically give nine days extension for Assignment 2. It will be to your own advantage to check whether the assignment has been registered on the system after a few days. If you want to submit the assignment electronically and myUnisa is off-line during that time, you need not contact us, because we will be aware of it. Simply submit it as soon as myUnisa is available again.

DUE DATE

20 March

EXTENSION

There is an automatic extension date namely 29 March. Do not phone or send e-mail. Study Guide, Lessons 1 - 22 70%

TUTORIAL MATTER WEIGHT OF CONTRIBUTION TO SEMESTER MARK NO unique number

IS YOUR SOFTWARE (both the compiler and the IDE) INSTALLED? Read Appendix 1 of this tutorial letter. Look at Troubleshooting under Using the software in file index.html on Disk 2009 or in Appendix 1 of this tutorial letter if your programs do not compile. If your output flashes on the screen and then disappears, you are storing the programs incorrectly. The names of the folders where the programs are stored should not contain space characters, for example My Documents is not permissible. Create a folder cos111 directly below c:\unisa and store your programs there (with names without space characters). PLEASE TURN OVER

38

QUESTION 1 In this question only short answers should be written down. Question 1a Suppose we want to input and validate three characters in a do..while loop. The variable names are c1, c2 and c3. The values of c1 and c2 may not be the same and c3 may not be equal to X. If this condition does not hold, the loop has to be executed again. Write down a correct condition for the do..while loop. Question 1b Suppose we want to input and validate three integers in a do..while loop. The variable names are n1, n2 and n3. The requirement is that the sum of the three integers is less than 1000 or that n3 is greater than 100. If this condition does not hold, the loop has to be executed again. Write down a correct condition for the do..while loop. Question 1c Write down the output when the following fragment of a C++ program is executed: int n = 55; for (int i = 1; i < 4; i++) n = n - i * 4; cout << n << endl; Question 1d Suppose Hannah wants to save for six months. She saves R150 during the first month and plans to save every month R20 more than the previous month. Complete the for loop in the C++ program fragment below to calculate the total amount that is saved. float monthSave, totalSave; totalSave = 150; monthSave = 150; for ( ; ; ) {

} cout << "In 6 months Hannah saved R" << totalSave;

QUESTION 2: NESTED LOOPS Suppose a new member of the city council has to be chosen from three candidates and suppose there are 4 voting stations. We need a C++ program that will count the votes for every candidate and display the result. At every voting station the voters have to be asked one after the other for which candidate (indicated by A or B or C) he or she wants to vote. X is entered when all the voters at the specific voting station have voted. The program has the following structure:

39

COS111U/101/3/2009

The three totals and the number of spoilt votes are initialised to 0. Now a for loop follows, going from 1 to the number of voting stations. Inside this loop is a while loop. A prompting message appears on the screen, asking the voter for which candidate he or she wants to vote. The choice of the voter is then input. Inside the while loop is a switch statement to increment the correct total. The default option is used to count the number of spoilt votes. The while loop is exited when X is entered for the choice. When the for loop is exited, the three totals and the number of spoilt votes are displayed.

To help you we give the following framework: #include <iostream> using namespace std; int main( ) { const int NR_VOTING_STATIONS = 4; int votesForA, votesForB, votesForC, spoiltVotes; char vote; // initialise totals // loop over the voting stations for ( ; ; ) { // loop over voters while ( { )

} } // display results cout << endl << endl; cout << "Total candidate A: " << votesForA << cout << "Total candidate B: " << votesForB << cout << "Total candidate C: " << votesForC << cout << "Total spoilt votes: " << spoiltVotes return 0; } Run your program with the input given below and submit printouts of the program and output. (We write the data of each voting station in one line, but you will possibly enter the values on separate lines.) BBBACX ABCDYBX

endl; endl; endl; << endl;

40

BACCBX ABX QUESTION 3: VALUE RETURNING FUNCTIONS WITH ONE AND TWO VALUE PARAMETERS

Peter Mobake is the manager of a packaging business where all the containers have one size, namely 2000cm3. He needs a C++ program that will determine how many containers will be needed for every order. For example: If the items are all of size 25cm3, the number that will fit into one container is

2000 80 . If 200 items should be packed, 25

3 containers will be needed. The program should also calculate the fee that is due. We are going to develop the program in four steps. You need to submit the program and output of question 3d only. You will see that several global int constants are declared. Question 3a: Start small

We give the main function below. Your task is to write a function, namely nrFitInContainer, of return type int. There is one value parameter only. The function receives an int value, namely the size of the individual items that should be packed. The function should then calculate how many of these items will fit into one container and return the answer as an integer. Test your program with several input values but do not submit any printouts. // Assignment 2 Question 3a #include <iostream> using namespace std; const int CONTAINER_SIZE = 2000; // The required function nrFitInContainer should be inserted here. int main( ) { int size, nrInEveryContainer; cout << "What is the size of every item? "; cin >> size; if (size > CONTAINER_SIZE) cout << "Items are too big. Sorry, we cannot help you." << endl << endl; else { nrInEveryContainer = nrFitInContainer(size); cout << nrInEveryContainer << " items fit into one container." << endl; } return 0; }

41

COS111U/101/3/2009

Question 3b: Slightly larger


We again give the main function below. Now write another value returning function of return type int, namely nrContainers. There are two value parameters. The function receives the number of items that should be packed (thus a parameter of type int) and the number of items that will fit into one container (thus also a parameter of type int). Then the function has to calculate how many containers will be necessary and return the answer as an integer. Test your program with several input values but do not submit any printouts. // Assignment 2 Question 3b #include <iostream> using namespace std; const int CONTAINER_SIZE = 2000; // The required functions nrFitInContainer and nrContainers should be // inserted here. int main( ) { int size, nrToBePacked; int nrInEveryContainer, nrContainersNeeded; cout << "What is the size of every item? "; cin >> size; if (size > CONTAINER_SIZE) cout << "Items are too big. Sorry, we cannot help you." << endl << endl; else { cout << "How many items should be packed? "; cin >> nrToBePacked; nrInEveryContainer = nrFitInContainer(size); nrContainersNeeded = nrContainers(nrToBePacked, nrInEveryContainer); cout << nrContainersNeeded << " containers are needed for this job." << endl; } return 0; }

42

Question 3c:

Larger

The fee that customers have to pay for the packaging of the items depends on the number of containers as well as on the number of items in every container: If fewer than 10 containers will be used, the fee is R50 per container. If 10 or more containers are needed, the fee is R40 per container if there are fewer than 20 items in every container and R45 per container if there are 20 or more items in every container. We again give the main function below. Now write a value returning function, namely fee, of return type int. There are two value parameters. The function receives the number of containers that are needed (thus a parameter of type int) and the number of items that fit into one container (thus also a parameter of type int). The function then has to calculate the fee and return the answer as an integer. Test your program with several input values but do not submit any printouts. // Assignment 2 Question 3c #include <iostream> using namespace std; const const const const int int int int CONTAINER_SIZE = 2000; FEE_1 = 50; FEE_2 = 40; FEE_3 = 45;

// The required functions nrFitInContainer, // nrContainers and fee should be inserted here. int main( ) { int size, nrToBePacked; int nrInEveryContainer, nrContainersNeeded, amountDue; cout << "What is the size of every item? "; cin >> size; if (size > CONTAINER_SIZE) cout << "Items are too big. Sorry, we cannot help you." << endl << endl; else { cout << "How many items should be packed? "; cin >> nrToBePacked; nrInEveryContainer = nrFitInContainer(size); nrContainersNeeded = nrContainers(nrToBePacked, nrInEveryContainer); amountDue = fee(nrContainersNeeded, nrInEveryContainer); cout << "Fee: R" << amountDue << endl << endl; } return 0; }

43

COS111U/101/3/2009

Question 3d:

Add a loop to the main function

Write a program containing the functions nrFitInContainer, nrContainers and fee that you wrote in 3a, 3b and 3c. The program has to process a list of orders and display the fee in every case. You may use the main function of 3c but you will have to change it as it should now contain a for loop. Run your program on the list of 5 orders below and submit printouts of the program and the output. The first entry on every line is the size and the second entry is the number of items. 33 20 3333 400 500 100 1000 22 20 1000

QUESTION 4:

void FUNCTIONS WITH ONE OR MORE VALUE PARAMETERS

You should only submit printouts for question 4c. Suppose we want to display the following figure containing a triangle on the screen: ^^^^^#^^^^^ ^^^^###^^^^ ^^^#####^^^ ^^#######^^ ^#########^ ########### We want to be able to specify the size of the figure. The size of the figure given above is 5. It means that the first row of the figure consists of 5 ^ characters followed by one # followed by 5 ^ characters. There is one row more than the specified size (i.e. 6 rows in this case). The figure will look as follows if the size is 7: ^^^^^^^#^^^^^^^ ^^^^^^###^^^^^^ ^^^^^#####^^^^^ ^^^^#######^^^^ ^^^#########^^^ ^^###########^^ ^#############^ ############### Question 4a: One value parameter

Write a void function drawShape that displays such a figure on the screen. There has to be one parameter (of type int), namely the size as indicated above. Use the main function given below and input 5 as the size. Make sure that the figure is correct, but do not submit printouts of the program or the output.

44

Hint: Use for loops. Suppose sizeP contains the size. Then the i-th row should start with (sizeP - i + 1) ^ characters, followed by (2 * i - 1) # characters, followed by another (sizeP - i + 1) ^ characters. There should be (2 * sizeP + 1) # characters in the last row. // Assignment 2 Question 4a #include <iostream> using namespace std; // The required function drawShape should be inserted here. int main( ) { int size; cout << "Size: "; cin >> size; drawShape(size); return 0; } Question 4b: Two value parameters

In 4a the # character formed the triangle in the figure. Change function drawShape in such a way that we will be able to specify what character should form this triangle. We give the new main function below. You will see that two values are now input in the main function, namely the size and the character that should form the triangle. Function drawShape now should have two parameters, one of type int (namely the size) and one of type char (namely the character that has to form the triangle). Input 5 as the size and @ as the character and make sure that the figure is correct but do not submit printouts of the program or output. // Assignment 2 Question 4b #include <iostream> using namespace std; // The required function drawShape should be inserted here. int main( ) { int size; char charTri; cout << "Size: "; cin >> size; cout << "Triangle character: "; cin >> charTri; drawShape(size, charTri); return 0; }

45

COS111U/101/3/2009

Question 4c:

Three value parameters

In 4a and 4b the ^ character filled the background of the figure. Change function drawShape in such a way that we will be able to specify what character should fill the background. The function drawShape will thus have three value parameters, namely one of type int (the size) and two of type char (the triangle character and the background character, respectively). We do not give the main function again. You should change both the main function and function drawShape. Run your program with 16 as the size, % as the triangle character and # as the background character. Submit printouts of the program and the output.

QUESTION 5:

void FUNCTIONS WITH DIFFERENT TYPES AND NUMBERS OF PARAMETERS

Richard Rawlings, the coach of the Lions (the first team of the LionHeart soccer club) wants to compare the scores of matches played at home and matches played away from home. He decides to calculate four averages, namely the average number of goals scored by his team when they play at home, the average number of goals scored by the opponents when the match is played at home, the average number of goals scored by his team when they play away from home, and the average number of goals scored by the opponents when the match is played away from home. Write a C++ program to help Richard with this. The program is developed in three steps. You have to submit printouts for 5c only. Question 5a: Three reference parameters

Write a void function inputAndValidate where the scores of one match are input and validated. The function should have three reference parameters, namely a parameter that stores the number of goals scored by the Lions (thus of type int), a parameter that stores the number of goals scored against the Lions (thus also of type int) and a parameter that indicates whether the match was played at home or away from home. This (third) parameter is of type char: H indicates a home match and A indicates a match played away from home. The third parameter has to be validated by using a do..while loop: the program should keep on displaying a prompting message until the user enters either H or A. We give the main function below. Test your program to make sure that it works correctly, but do not submit any printouts. // Assignment 2 Question 5a #include <iostream> using namespace std; // The required function inputAndValidate should be inserted here. int main( ) { int pointsFor, pointsAgainst; char where; inputAndValidate(pointsFor, pointsAgainst, where); cout << "The result of the match was " << pointsFor << "-"

46

<< pointsAgainst << " and the match was played "; if (where == 'H') cout << "at home." << endl; else cout << "away from home." << endl; return 0; } Question 5b: Two value parameters and two reference parameters

In order to calculate the four averages that the coach wants, we have to update the correct totals after every match. We have to consider four totals, namely the total number of points scored by the Lions in home matches, the total number of points scored against the Lions in home matches, the total number of points scored by the Lions in matches played away from home, and the total number of points scored against the Lions in matches played away from home. In order to calculate the averages we also need to know how many home matches and how many away matches were played. Now write two void functions updateTotalsHome and updateTotalsAway that update the correct totals. Each of these functions has two value parameters that supply the outcome of the specific match to the function (thus the Lions points and their opponents points) and two reference parameters, namely two totals. Every time the specific function is called, these totals will change by adding the number of points scored by the Lions and the number of points scored by their opponents to the respective totals. We give the main function below. Test your program but do not submit any printouts. / Assignment 2 Question 5b #include <iostream> using namespace std; // The required functions updateAndValidate, updateTotalsHome // and updateTotalsAway should be inserted here int main( ) { int pointsFor, pointsAgainst; int totalForHome, totalAgainstHome, totalForAway, totalAgainstAway; int nrHome, nrAway; char where; // initialise totals totalForHome = 0; totalAgainstHome = 0; totalForAway = 0; totalAgainstAway = 0; nrHome = 0; nrAway = 0;

47

COS111U/101/3/2009

inputAndValidate(pointsFor, pointsAgainst, where); if (where == 'H') { nrHome++; updateTotalsHome(pointsFor, pointsAgainst, totalForHome, totalAgainstHome); } else { nrAway++; updateTotalsAway(pointsFor, pointsAgainst, totalForAway, totalAgainstAway); } cout << "The totals at this point is: " << totalForHome << " " << totalAgainstHome << " " << totalForAway << " " << totalAgainstAway << endl; return 0; } Question 5c: Final version

Declare a global constant NR_MATCHES and assign the value 9 to it. Now write a new main function containing a for loop going from 1 to NR_MATCHES. The three functions that you wrote in 5a and 5b should be called inside this loop. When the loop is exited, the four averages should be calculated and displayed. Give the averages as floating point numbers. Run your program on the data below. (The Lions score is always given first.) Submit printouts of the program and output. 3 H 4 h H 2 A 0 A 2 A 2 H 2 A 2 h H 3 a 3 2

4 3 2 2 3 0

1 TURN OVER

48

QUESTION 6:

FUNCTION CALLS

In this question you should write down short answers only. A function header is given and you have to write down a correct function call. You also have to declare all the variables that you use in the calling statement. Example: If the function header float price(string descriptionP) is given, a correct answer will be: float priceOfItem; string description; priceOfItem = price(description); Question 6a bool yesOrNo(int yearP) Question 6b int year(string modelP, int capP) Question 6c void calcTwoMarks(char & symb1P, char & symb2P) Question 6d void findNames(string addressP, char & initP, string & surnameP)

QUESTION 7:

DECIDE YOURSELF

The GreatParty restaurant may be booked for parties in the evenings. Each guest at the party has to indicate in advance which menu out of three fixed menus he or she wants. The prices of menus A, B and C are R90, R100 and R120, respectively. The group has to consist of al least 20 and at most 50 guests. Suzanne, the manager of the restaurant, wants a C++ program that she can run at the beginning of every week. For each of the seven evenings the program has to: input the bookings for that evening, thus the number of persons for each of the three menu choices. validate the booking if there are not going to be between 20 and 50 guests, a message has to be displayed indicating that the booking is impermissible. The user should then repeatedly be prompted to enter the three numbers again until the input is correct. display the number of guests and the expected income for that evening. You have to write this program. The program should consist of five functions. Declare constants for the prices of the three menus, the minimum and maximum number of guests and the number of evenings.

49

COS111U/101/3/2009

Main function: Declare the following variables: int nrMenuA, nrMenuB, nrMenuC, nrTotal; float income; Use a for loop going from 1 to the number of evenings (namely 7). The other four functions should be called inside the loop. Function inputInformation: This function handles the input. It inputs the number of guests that will order Menu A, Menu B and Menu C, respectively. The function has to make sure that the total number of guests will be at least 20 and at most 50. If this is not the case, a prompting message should be displayed and the three numbers should be entered repeatedly until the total is between 20 and 50. You have to decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Function nrPartyGoers: This function calculates the number of guests that will be in the restaurant on that specific evening. You have to decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Function incomeOneNight: This function calculates the expected income of the specific booking. You have to decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Function displayNumberAndAmount: This function displays the number of guests and the expected income on the specific evening. You have to decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Run your program on the data below. Submit printouts of the program and output. 33 11 44 14 0 33 15 7 9 22 44 14 25 0 15 7 6 0 44 14 25 11 15 7

50

ASSIGNMENT 3

FIRST SEMESTER

Submission: The assignment should NOT be submitted.


You should assess it yourself when you receive the model solution. Note that there will be examination questions set on this part of the Study Guide also.

DUE DATE EXTENSION TUTORIAL MATTER

27 April Not applicable Study Guide, Lessons 1 to 29. Note that Lesson 30 is not examination material. It is meant for enrichment. 0%

WEIGHT OF CONTRIBUTION TO SEMESTER MARK NO unique number QUESTION 1: VARIABLE DIAGRAMS REVISITED

Draw a series of variable diagrams for the program below. Use the conventions of the Study Guide. Compare your answers to the model solution. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // variable diagrams revisited #include <iostream> using namespace std; const int AA = 300; int func1(int n, int n1) { n -= 3; n1 += n; return 2 * n * n1 + AA; } void func2(int n, int & n1) { n = 2 * AA; n1 = n n1; } void func3(int & n, int & n1) { int k; k = n1 * 3; n = k + 30;

51

COS111U/101/3/2009

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

n1 = k + 2 * n; } int main( ) { int n, m, j; n = 5; m = 10; j = func1(n, m); n = 15; m = 20; func2(n, m); n = 25; m = 30; func3(n, m); return 0; }

QUESTION 2:

ONE-DIMENSIONAL ARRAYS

We have to write a program to display the names of soccer players who received more (yellow or red) cards than the number of goals scored by them. The names of the players are given but the number of goals scored and the number of cards received by each player have to be input. Declare a global constant, namely NR_PLAYERS, and set it equal to 12. The program should consist of four functions. No global variables may be used. The main function: Declare the following four one-dimensional arrays: names of type string where the 12 names (see below) will be stored, goals of type int where the number of goals scored by the players will be input, cards of type int where the number of cards received by the players will be input, namesMore of type string where the names of the players with more cards than goals will be stored. The array names should be initialised in its declaration. The strings to be stored are: "Tiny Nakedi", "Cecil Mametsa", "Chris Rooney", "Mario Thomas", "Frank Ntini", "Charlie Ashley", "Morio Zondo", "Khabo Mosimane", "Pitso Hack", "Lloyd Mokoena", "Rick Smith", "Kabelo Ramago". The main function has to call the other three functions one after the other. We give the type of everyone of the other functions but you have to decide yourself on the number and type(s) of the parameter(s). Use the conventions of the Study Guide. The void function inputInformation: The information about goals and cards are input here. The function should contain a for loop. Every time that the loop is executed, the name of a player should be displayed and then the number of goals scored and the number of cards received by that player have to be entered..

52

The void function findPlayersWithMoreCardsThanGoals: The function should contain a for loop. Every time that the loop is executed, the number of cards and the number of goals of the relevant player should be compared. If the number of cards is greater than the number of goals, the name of the player should be stored in a separate array. (Thus the name of the first player with more cards than goals is placed in the first element of this new array, the name of the second player with more cards than goals is placed in the second element of the new array, et cetera.) The function should also determine the number of players whose names appear in this array and should make it available to the main function. The void function displayInfo: The function has to display the names of all players with more cards than goals. Run your program on the data below. The first number is the number of goals scored by the player and the second number is the number of cards that the player received. The data is in the same order as the names listed above. Compare your output to that of the model solution. 4 0 0 1 2 1 1 2 2 2 4 5 2 0 3 2 2 3 0 4 1 2 5 6

QUESTION 3: TWO-DIMENSIONAL ARRAYS Four friends, Aggie, Bruce, Cecil and Danita, are registered for the three modules ABC111, DEF222 and GHI333. The number of hours each of them spends weekly on his or her studies are given in the following table: ABC111 11 9 8 12 DEF222 9 10 8 8 GHI333 7 13 8 9

Aggie Bruce Cecil Danita

Write a program consisting of a main function and three other functions. The main function has to call the other three functions. You are not allowed to use any global variables but you should declare two global constants, namely NR_FRIENDS and NR_MODULES. The program should do the following: Input the various numbers of hours row by row and store it in a two-dimensional array with four rows and three columns. The values should be input in the void function inputHours. Compute the total study hours of each friend and then display the smallest of these four totals. All the computations should be done in the int function hoursLeast. The smallest total should be returned to the main function and displayed there.

53

COS111U/101/3/2009

Display the average number of hours spent on each module. The computation of the averages should be done in the void function displayAverages and they should also be displayed there.

Run your program on the data and compare your output to that of the model solution.

QUESTION 4:

STRINGS DELETE AND INSERT

Write a program consisting of a main function and one other function. A string should be input in the main function and then the string function changedString should be called. The function should do the following: Delete every odd occurrence of t. Thus delete the first, third, fifth, etc occurrence of t in the given string. Insert h after every even occurrence of t. Thus insert h after the second, fourth, sixth, etc occurrence of t in the original string. Suppose the string The cats and the rats teeth will stop any tortoise. is input. Then the following string should be returned to the main function: The cas and thhe ras theeh will sthop any orthoise. No global variables may be used. Use a while loop in the main function and execute the loop until NOTHING MORE is input. Run the program on the strings below and compare your output to that of the model solution. This is not the first time that this has happened, or is it? Katte en tarentale rym met latte en liniale. It is a pity that Kitty is very pretty. There is the thing I want. Lettie thinks the theory is true. NOTHING MORE

QUESTION 5:

MORE STRINGS

In this question you have to write a program consisting of three functions. A string has to be input in the main function. If the string has odd length, a string function doubledString should be called to double the string. Thus, if the string was Ben, it should be changed to BenBen. (The string will now be of even length.) Then another string function, namely expandedString, should repeatedly be called to expand the string. This is done by inserting the central two characters into the centre of the string. If, for example, the string is 123456, it will be 12334456 after the first call of expandedString, it will be 1233344456 after the second call of expandedString, it will be 123333444456 after the third call of expandedString, et cetera. Main function: Use a for loop to process six strings. Inside the loop a string has to be input. If the length of the string is an odd number, the string function doubledString should be called. After this call the string will be of even length. Then the string function expandedString has to be called repeatedly until the string becomes longer than 40 characters.

54

Function doubledString: The function receives a string and returns the doubled string. If, for example, the string qwertyu is received, qwertyuqwertyu should be returned. Function expandedString: The function receives a string of even length and expands it by inserting the two central characters into the centre of the string. If, for example, the function receives the string Hi Johnie! the string Hi Joohhnie! should be returned. No global variables may be used. Run your program on the strings below and compare your output to that of the model solution. Cheers! String manipulation is easy. Only two questions remain to be done. Hier gaan ons al weer. Can you believe it? !@#$%^&*

QUESTION 6:

GARDEN SERVICES

FloraServices is n firm that services gardens. They work once a week for three hours in the garden of each of their customers. The following information is available for each of the gardens currently serviced by them: address (a string, for example 44 Main Street) day of the week on which the specific garden is serviced (a string, for example Monday) number of gardeners working together in the specific garden (an integer, for example 4) an indication whether there is a swimming pool in the garden (a character, namely Y if there is a pool, and N if not). You have to write a program to provide the management with certain information. Question 6a: Declare a struct

Write down the declaration of a struct for storing the information about a single garden. Give the name GardenInfo to the struct. Question 6b: An array of structs

Write down the declaration of a constant NR_OF_GARDENS and set it equal to 12. Then write down the declaration of an array of 12 structs that will contain the information about 12 gardens. Question 6c: A function to input the information

Write a function inputInformation that inputs the information about 12 gardens. The function header should be void inputInformation(GardenInfo gardensP[])

55

COS111U/101/3/2009

Use a do..while loop to validate the input about the presence of a swimming pool, thus a prompting message should appear, repeatedly asking that either Y or N be entered until it is done. Question 6d: A function to display specific information

Write a function displaySomeInformation to display the following three groups of information: (i) the addresses of all gardens serviced on Tuesdays, (ii) for all gardens in Long street that have pools, the days on which they are serviced and the number of gardeners working there, (iii) the addresses of all gardens requiring more than 4 gardeners at a time. The function header should be void displaySomeInformation(const GardenInfo gardensP[]) Question 6e: A complete program

Write a main function that calls the other functions. Use the declarations and functions above to form a complete program. No global variables may be used. Run your program on the data below and compare your output to that of the model solution. 33 Mandela street Manfred House 123 Long street 5 Oak Avenue 555 Long street 999 Long street 2 Main street Kiepersol Park 456 Long street Central Square Flora Park 50 Long street Monday Friday Tuesday Tuesday Thursday Wednesday Tuesday Monday Wednesday Monday Thursday Friday 3 6 3 4 2 6 1 7 2 7 5 3 Y Y Y N N Y N N Y N N Y

56

Section 12

THE ASSIGNMENTS OF THE SECOND SEMESTER ASSIGNMENT 1 SECOND SEMESTER

(MULTIPLE CHOICE) SUBMISSION: On multiple choice form or electronically through myUnisa

Please note that Assignment 1 has to be submitted in order to gain examination admission. It will be to your own advantage to check whether the assignment has been registered on the system after a few days. If you want to submit the assignment electronically and myUnisa is off-line during that time, you need not contact us, because we will be aware of it. Simply submit it as soon as myUnisa is available again.

DUE DATE EXTENSION TUTORIAL MATTER WEIGHT OF CONTRIBUTION TO SEMESTER MARK UNIQUE NUMBER QUESTIONS

21 August NO extension will be granted for Assignment 1. Study Guide, Lessons 1 - 13 30%

169344

45 questions. 5 options each. Choose one option in every question.

IS YOUR SOFTWARE (both the compiler and the IDE) INSTALLED? Read Appendix 1 of this tutorial letter. Look at Troubleshooting under Using the software in file index.html on Disk 2009 or in Appendix 1 of this tutorial letter if your programs do not compile. If your output flashes on the screen and then disappears, you are probably storing the programs incorrectly. The names of the folders where the programs are stored should not contain space characters, for example My Documents is not permissible. Create a folder cos111 directly below c:\unisa and store your programs there. The names of the programs should also not contain any space characters.

PLEASE TURN OVER

57

COS111U/101/3/2009

Hint: In many of these questions you should type in a short C++ program, compile and run it in order to select the correct option.

Question 1 After the file index.html on Disk 2009 has been opened and after the link to COS111U has been clicked, information appears regarding, amongst others, the installation of the software. Which of the following options is correct? 1. 2. 3. 4. 5. Both the compiler and the IDE may be installed by Method 1. Only the compiler needs to be installed by one of the methods. Only the IDE needs to be installed by one of the methods. The compiler has to be installed by Method 1 and the IDE by Method 2. It is unnecessary to install anything.

Question 2 When you save a program, you should click on File and then on Save or on Save as. The name of the file and the name of the folder where it will be stored, have to be indicated. Which of the following options is correct? 1. 2. 3. 4. 5. Create a folder with the name COS 111 under c:\unisa and store the program there. Create a folder with the name cos111 under c:\unisa and store the program there. The name Activity 3a is a permissible name for the file. It is permissible to store the program in the folder My Documents. Any folder will be correct.

Questions 3, 4, 5 and 6 are based on the following C++ program: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // Program for assignment 1 of 2009. Questions 3 - 6. #include <iostream> using namespace std; int main( ) { const float FARE_ADULT = 10.55; const float FARE_CHILD = 6.45; CONST int MAX_PASSENGERS = 13; char a; int totalPassengers; totalPassengers = 0 do { cout << "Are you older than 10? Answer Y or N: "; cin >> a; if (a == 'N') cout << "Please pay R" << FARE_CHILD << endl;

58

20 21 22 23 24 25 26 27

else cout << "Please pay R" << FARE_ADULT << endl; totalPassengers++; } while (totalPassengers << MAX_PASSENGERS); return 0; }

Question 3 Which of the following options would rectify the syntax error in line 9? 1 2 3 4 5 Question 4 Which of the following options would rectify the syntax error in line 13? 1 2 3 4 5 Question 5 Which of the following options would rectify the syntax error in line 18? 1 2 3 4 5 Change the statement to if (a == 'N'); Change the statement to if (a = 'N') Change the statement to if (answer == 'N') Change the statement to if (a == 'N'||'n') There is no error, so nothing should be done. Change the statement to totalPassengers == 0; Change the statement to totalPassengers = 0; Switch the statements in lines 14 and 15 around. Change the statement in line 12 to // initialize: There is no error, so nothing should be done. Change the statement to CONST INT MAX_PASSENGERS = 13; Change the statement to const int MAX_PASSENGERS = 13; Change the statement to const INT MAX_PASSENGERS = 13; Change the statement to CONST int MAX_PASSENGERS == 13; There is no error, so nothing should be done.

59

COS111U/101/3/2009

Question 6 Which of the following options would rectify the syntax error in line 24? 1 2 3 4 5 Change the statement to while (totalPassengers >> MAX_PASSENGERS); Change the statement to while (totalPassengers << MAX_PASSENGERS) Change the statement to while (totalPassengers = MAX_PASSENGERS); Change the statement to while (totalPassengers < MAX_PASSENGERS); There is no error, so nothing should be done.

Questions 7 and 8 are based on the following: Patrick sells milk to the public in 5 litre containers. Suppose three variables totalLitres, nrContainers, and litresLeftOver have been declared as int and suppose a value has already been assigned to totalLitres (the total quantity of available milk). Question 7 Which of the following options is a correct C++ instruction to calculate the number of containers filled with milk that can be sold? 1. 2. 3. 4. 5. nrContainers nrContainers nrContainers nrContainers nrContainers = totalLitres - litresLeftOver; /= 5; = totalLitres / 5; = totalLitres % 5; = litresLeftOver * 5;

Question 8 Which of the following options is a correct C++ instruction to calculate the number of litres that will be left over? 1. 2. 3. 4. 5. litresLeftOver litresLeftOver litresLeftOver litresLeftOver litresLeftOver = totalLitres - nrContainers; /= 5; = totalLitres / 5; = totalLitres % 5; = nrContainers * 5;

Questions 9, 10, 11, 12 and 13 are based on the following program: 1 2 3 4 5 6 7 // Program for assignment 1 of 2009. Questions 9 - 13. #include <iostream> using namespace std; int main( ) { int n1, n2, n3, i;

60

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

n1 = 222; n2 = n1--; n3 = 'E' + 'F'; i = 2; n1 = 10; while(i < 4) { n1 *= 2; n2 = 4 + n1 * i; n3 = i * 111 / 2 * i; i++; } n1 = 88; n2 = ++n1; n3 = n1++; return 0; }

Question 9 Which of the options below correctly reflects the situation after Line 11 has been executed? Option 1 Line 11 n1 221 n1 222 n1 221 n1 222 n2 221 n2 221 n2 222 n2 222 n3 139 n3 'K' n3 139 n3 'K' i ? i ? i ? i 0

Option 2

Line 11

Option 3

Line 11

Option 4

Line 11

Option 5

Line 11

None of the above options is correct.

61

COS111U/101/3/2009

Question 10 Which of the options below correctly reflects the situation after Line 18 has been executed the first time? Option 1 Line 18 n1 20 n1 20 n1 20 n1 2 n2 44 n2 48 n2 44 n2 8 n3 222 n3 222 n3 55 n3 55 i 2 i 2 i 2 i 2

Option 2

Line 18

Option 3

Line 18

Option 4

Line 18

Option 5

Line 18

None of the above options is correct.

Question 11 Which of the options below correctly reflects the situation after Line 18 has been executed the second time? Option 1 Line 18 n1 2 n1 2 n1 40 n1 40 n2 10 n2 18 n2 132 n2 124 n3 499.5 n3 498 n3 498 n3 498 i 3 i 3 i 3 i 3

Option 2

Line 18

Option 3

Line 18

Option 4

Line 18

Option 5

Line 18

None of the above options is correct.

62

Question 12 Which of the options below correctly reflects the situation after Line 23 has been executed? Option 1 Line 23 n1 89 n1 89 n1 89 n1 89 n2 88 n2 89 n2 88 n2 89 n3 498 n3 498 n3 498 n3 498 i 4 i 4

Option 2

Line 23

Option 3

Line 23

Option 4

Line 23

Option 5

Line 23

None of the above options is correct.

Question 13 Which of the options below correctly reflects the situation after Line 24 has been executed? Option 1 Line 24 n1 90 n1 90 n1 90 n1 90 n2 89 n2 88 n2 89 n2 88 n3 89 n3 90 n3 89 n3 90 i 4 i 4

Option 2

Line 24

Option 3

Line 24

Option 4

Line 24

Option 5

Line 24

None of the above options is correct.

Question 14 Which option indicates the output of the following program? #include <iostream> using namespace std; int main( ) { float a, b;

63

COS111U/101/3/2009

a = 34.56789; b = 54.321; a *= b; cout.setf(ios::fixed); cout.precision(2); cout << a << " and " << b << endl; return 0; } 1. 2. 3. 4. 5. 1877.76 and 54.32 1877.76 and 54.321 1877.76 and 1877.76 a and b None of the above options indicates the correct output.

Questions 15 and 16 are based on the following program: #include <iostream> using namespace std; int main( ) { char c1, c2, c3; cout << "Enter two characters: "; cin >> c1 >> c2; c3 = c1 + c2 - 95; cout << "New character is " << c3 << endl; return 0; } Question 15 Type in the program given above, compile it and then run it with the following input: 6 7 Which option gives the output? 1. 2. 3. 4. 5. New character is New character is New character is -82 New character is c3 None of the above options indicates the correct output.

64

Question 16 Run the above program again but with the following input: A Z Which option gives the output? 1. 2. 3. 4. 5. New character is New character is A + Z - 95 New character is < New character is c3 None of the above options indicates the correct output.

Questions 17 and 18 are based on the following program: # include <iostream> #include <string> using namespace std; int main( ) { string s1, s2, s3; cout << "Provide input, please: " << endl; getline(cin, s1, '\n'); cin >> s2; cin.get( ); getline(cin, s3, '\n'); cout << s1 << endl << s2 << endl; cout << s3 << endl; return 0; } Question 17 Type in the above program, compile it and then run it with the following input: My Bonnie lies over the ocean. My Bonnie lies over the sea. Which option gives the output? 1. My Bonnie lies over the ocean. My 2. My Bonnie lies over the ocean. My Bonnie lies over the sea. The computer will wait for you to enter another string.

65

COS111U/101/3/2009

3. My Bonnie lies over the ocean. My Bonnie lies over the sea. 4. My Bonnie lies over the ocean. My Bonnie lies over the sea. 5. None of the above options indicates the correct output. Question 18 Run the above program again but with the following input: The train leaves at 7:30. PM? No, in the morning. Which option gives the output? 1. The train leaves at 7:30. PM? No, in the morning. 2. The train leaves 3. The train leaves at 7:30. No, 4. The train leaves at 7 :30. PM? No, in the morning. 5. None of the above options indicates the correct output. Question 19 Suppose we have to swop the values of two int variables num1 and num2 if num1 > num2. Which of the following options gives the correct C++ instructions to do this? 1. if (num1 > num2) { int temp = num1; num1 = num2; num2 = temp; } 2. if (num1 > num2) int temp = num2; num2 = num1; num1 = temp;

66

3. if (num1 > num2) { num1 = num2; num2 = num1; } 4. if (num1 > num2) num1 = num2; num2 = num1; 5. None of the above options is correct or more than one of the options is correct. Question 20 Suppose we have to multiply the value of a float variable amount with the value of an int variable numberTrans if numberTrans is not zero. The result has to be stored in the float variable totalAmount. Which of the following options gives the correct C++ instruction to do this? 1. if (numberTrans = 0) totalAmount = amount * numberTrans; 2. if (numberTrans != 0) totalAmount = amount * numberTrans; 3. if (numberTrans != 0) totalAmount == amount * numberTrans; 4. if (numberTrans == 0) totalAmount = amount * numberTrans; 5. None of the above options is correct. Question 21 Suppose the height of an aspirant police officer is stored in the float variable height. Which of the following options is a correct C++ instruction to display an applicable message about the height? 1. if (height > 1.80) cout << "Height greater than 1.80"; cout << "Height not greater than 1.80"; 2. if (height > 1.80) cout << " Height greater than 1.80"; else; cout << " Height not greater than 1.80"; 3. if (height > 1.80) cout << " Height greater than 1.80"; else cout << " Height not greater than 1.80"; 4. if (height > 1.80m) cout << " Height greater than 1.80"; else cout << " Height not greater than 1.80"; 5. None of the above options is correct.

67

COS111U/101/3/2009

Question 22 Suppose two int variables n1 and n2 are initialised and then input repeatedly in the body of a while loop. The loop has to be executed as long as the value of n1 is not 0 and the value of n2 is not 10. Which of the options below is a correct condition for the while loop? 1. 2. 3. 4. 5. ((n1 != 0) && (n2 !=10)) ((n1 != 0) || (n2 != 10)) ((n1 == 0) && (n2 == 10)) ((n1 == 0) || (n2 == 10)) None of the above options is correct.

Question 23 Suppose two int variables n1 and n2 are initialised and then input repeatedly in the body of a while loop. The loop should be exited when the value of n1 or n2 is less than 123. Which of the options below is a correct condition for the while loop? 1. 2. 3. 4. 5. (!((n1 < 123) && (n2 < 123))) (!(n1 < 123) || !(n2 < 123)) ((n1 >= 123) && (n2 >= 123)) ((n1 >= 123) || (n2 >= 123)) None of the above options is correct.

Question 24 Suppose two char variables c1 and c2 and a string variable s1 are initialised. Then values are repeatedly assigned to c1, c2 and s1 in the body of a while loop. The loop has to be executed as long as c1 and c2 do not have the same value and the value of s1 is not NOBODY. Which of the options below is a correct condition for the while loop? 1. 2. 3. 4. 5. (!(c1 != c2) || (s1 == "NOBODY")) (!(c1 != c2) && (s1 == "NOBODY")) ((c1 == c2) || (s1 != "NOBODY")) ((c1 != c2) && (s1 != "NOBODY")) None of the above options is correct.

Question 25 In the program below the number of votes for two candidates, namely Mr A and Mr B, are counted. The program has, however, a logical error. Which of the options below the program will rectify the error? 1 2 3 4 5 6 7 8 # include <iostream> using namespace std; int main( ) { char vote; int mrA, mrB;

68

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 1. 2. 3. 4. 5.

mrA = 0; mrB = 0; cout << "First voter: Vote A or B (or Z to end) "; while (vote != 'Z') { if (vote == 'A') mrA++; else mrB++; cout << "Next voter: Vote A or B (or Z to end) "; cin >> vote; } cout << mrA << " votes for Mr A and " << mrB << " votes for Mr B." << endl; return 0; } Change line 11 to: cout << "First voter: "; Insert the following statement between lines 11 and 12: cin >> vote; Change line 16 to: else if (vote != 'A') Insert the following statement between lines 17 and 18: //next voter; None of the above options is correct.

Question 26 The program below deals with bunches of flowers. The number of flowers in each bunch is repeatedly entered, the total number of flowers and the number of bunches are determined and then the average number of flowers in a bunch is calculated. The program has, however, a logical error. Which of the options below the program will rectify the error? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 # include <iostream> using namespace std; int main( ) { int nrFlowers, nrBunches, totalFlowers, average; nrBunches = 0; totalFlowers = 0; cout << "Nr of flowers in first bunch (0 to end): "; cin >> nrFlowers; while (nrFlowers > 0) { nrBunches++; totalFlowers += nrFlowers; cout << "Nr of flowers in next bunch (0 to end): "; } if (nrBunches > 0) { average = totalFlowers / nrBunches;

69

COS111U/101/3/2009

21 22 23 24 25 26 1. 2. 3. 4.

cout << "Average number of flowers in a bunch is " << average << endl; } return 0; } Insert the following statement between lines 9 and 10: // initialise Change line 15 to: totalFlowers = totalFlowers + nrFlowers; Insert the following statement between lines 16 and 17: cin >> nrFlowers ; Insert the following statement between lines 22 and 23: else cout << "Average = 0" << endl; 5. None of the above options is correct.

Question 27 Suppose a familys surname is stored in the string variable surname and the number of pets in the int variable nrPets. Suppose further we want to assign the value true to a bool variable test if the familys surname is not Green and they have more than 2 but fewer than 7 pets. Which of the options below gives a correct assignment statement? 1. test = (2 < nrPets < 7) && (surname != "Green"); 2. test = (nrPets >= 2) && (nrPets <= 7) && (surname != "Green"); 3. test = (nrPets > 2) && (nrPets < 7) && !(surname == "Green"); 4. test =((nrPets > 2) || (nrPets < 7) || (surname != "Green"); 5. None of the above options is correct. Question 28 Suppose the following statement appears in a C++ program dealing with second hand cars: bool crit = cap > 1200 || year < 2002 && year >= 1992; where the variables cap (the capacity of the engine) and year (the year when the car was manufactured) have been declared as int already. Suppose further that the program contains a while loop starting as follows: while (crit) Which of the options below indicates when the loop will be executed? 1. The loop is executed if the engine capacity is more than 1200 or if the car was manufactured before 2002. The loop is also executed if the car was manufactured in 1992 or later. 2. The loop is executed if the engine capacity is more than 1200. The loop is also executed if the car was manufactured between 1992 and 2002, 1992 included but 2002 not. 3. The loop is executed only if the engine capacity is more than 1200 and the car was manufactured between 1992 and 2002, 1992 included but 2002 not. 4. The loop is executed if the engine capacity is more than 1200. The loop is also executed if the car was manufactured in 1992 or later. 5. None of the above options is correct.

70

Questions 29, 30 and 31 are based on the following fragment of a C++ program: string favourDrink, favourSnack; int grade; cout << "Enter favourite drink and snack, and school grade: "; cin >> favourDrink >> favourSnack >> grade; if (favourDrink != "HotChocolate") { if (favourDrink != "tea") if (favourSnack == "chips") cout << "Group A" << endl; else if (grade >= 8) cout << "Group B" << endl; else cout << "Group C" << endl; } else if (favourSnack == "chips" && grade == 10) cout << "Group D" << endl; Question 29 Which of the options below indicates the output if the following input is given? milk 1. 2. 3. 4. 5. chips 10

Group A Group B Group C Group D There is no output.

Question 30 Which of the options below indicates the output if the following input is given? HotChocolate 1. 2. 3. 4. 5. Group A Group B Group C Group D There is no output. chips 9

Question 31 Which of the options below indicates the output if the following input is given? coffee biltong 6

71

COS111U/101/3/2009

1. 2. 3. 4. 5.

Group A Group B Group C Group D There is no output.

Question 32 Suppose the variables age (the age of a town) and popul (the number of residents) are declared as int and the variable province (the province) as string. Suppose an estate agent is interested in towns with more than 5000 but less than 20000 residents. The towns should either be in Mpumelanga and older than 100 years, or should be older than 150 years. Which of the options below is a correct C++ statement to indicate these requirements?

1.

if (popul > 5000 && popul < 20000) { if (age > 100) if (province == "Mpumelanga") cout << "Yes yes" << endl; } else if (age > 150) cout << "Yes yes" << endl; if (popul > 5000 && popul < 20000) if (age > 100) { if (province == "Mpumelanga") cout << "Yes yes" << endl; } else if (age > 150) cout << "Yes yes" << endl; if (popul > 5000 && popul < 20000) if (age > 100) if (province == "Mpumelanga") cout << "Yes yes" << endl; else if (age > 150) cout << "Yes yes" << endl; if (popul > 5000 || popul < 20000) if (age > 150 && age > 100) if (province == "Mpumelanga") cout << "Yes yes" << endl; None of the options is correct.

2.

3.

4.

5.

72

Questions 33, 34 and 35 are based on the following fragment of a C++ program where we assume grade has been declared as int: switch(grade) { case 1: cout << "Excellent" << endl; case 2: cout << "Very good"; break; case 3: cout << "Good" << endl; case 4: cout << "Not good"; break; default: cout << "ERROR"; } Question 33 Which of the options below gives the output if the value of grade is the following? 10 1. 2. 3. 4. 5. Excellent Very good Good Not good None of the options gives the correct output.

Question 34 Which of the options below indicates the output if the value of grade is the following? 3 1. Good 2. Not good 3. Good Not good 4. GoodNot good 5. None of the options gives the correct output. Question 35 Which of the options below indicates the output if the value of grade is the following? 2 1. Very good 2. Very good Good 3. Very good Good 4. ERROR 5. None of the options gives the correct output

73

COS111U/101/3/2009

Question 36 A nursery school accepts children from 1 to 5 years of age. The children are placed into one of four groups, called Giraffes, Elephants, Klipspringers and Impala, respectively. Suppose we have a C++ program where the int variable age indicates the childs age and the int variable month indicates the birthday month of the child. Suppose further that the string variable group has to indicate the group into which the child should be placed. This is determined as follows: If the child is younger than 4, he or she has to be placed in the Impala group. If the child is 4 years old, the group should be Giraffes if his or her birthday falls in the first six months of the year, and Klipspringers if his or her birthday falls in the last six months of the year. If the child is 5 years old, he or she should be placed in the Elephants group. In a C++ program these assignments are done in a switch statement. Which of the following options gives a correct statement for this?

1.

switch(age) { case 1: case 2: case 3: group = "Impala"; case 4: if (month <= 6) group = "Giraffes"; else group = "Klipspringers"; case 5: group = "Elephants"; default: cout << "ERROR"; } switch(age) { case 1: case 2: case 3: group = "Impala"; break; case 4: if (month <= 6) group = "Giraffes"; else group = "Klipspringers"; break; case 5: group = "Elephants"; break; default: cout << "ERROR"; } switch(age) { case 1: case 2: case 3: group = "Impala"; break; case 4: if (month <= 6) group = "Giraffes"; else group = "Klipspringers"; case 5: group = "Elephants"; break; default: cout << "ERROR"; }

2.

3.

74

4.

5. Question 37

switch(age) { case 1: case 2: case 3: group = "Impala"; break; case 4: if (month <= 6) group = "Giraffes"; else group = "Klipspringers"; break; case 5: group = "Elephants"; default: cout << "ERROR"; } None of the options is correct.

Which of the options below is not a correct C++ variable name? 1. 2. 3. 4. 5. superfragilisticexpo HIthere version M3 R5555 All the options indicate a correct C++ variable name.

Question 38 Which of the options below is a correct C++ variable name? 1. 2. 3. 4. 5. 33rand goodMorningMomAndDad fish and chips 3+nr None of the above options is a correct C++ variable name.

Question 39 Which of the options below is not a correct C++ declaration of a constant? 1. 2. 3. 4. 5. const int NR_PASSENGERS; const string LAST_CLIENT = "nobody"; const float wishIknew = 5.5555; const bool CHECK = (3 == 3); All the options give a correct C++ declaration of a constant.

Question 40 Which of the options below is not a correct C++ instruction? 1. float time = 9.87; 2. if (p > 0) p--; else p++;

75

COS111U/101/3/2009

3. cout << p * p; 4. using NAMESPACE std; 5. All the options give a correct C++ instruction. Questions 41, 42, 43, 44 and 45 are based on the following: The C++ program below is supposed to determine the average age of the spectators at a soccer match. The age has to be input repeatedly until an age of 0 is entered. Then the average age has to be calculated and displayed. The number of spectators also has to be displayed. Five C++ statements have been omitted from the program. You have to answer questions 41 to 45 in order to complete the program. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #include <iostream> using namespace std; int main( ) { int age, nrSpectators, average; float total; total = 0; cout << "Enter age of first spectator: "; cin >> age; { nrSpectators++; total += age; cout << "Enter age of next spectator: "; } { average cout << cout << << } else = total / nrSpectators + 0.5; "Average age: " << average << endl; "Number of spectators: " << nrSpectators endl;

return 0; }

Question 41 Which of the options below gives a correct C++ instruction for line 8? 1. 2. 3. 4. average = totalAge / nrSpectators; nrSpectators = 0; nrSpectators = 1; totalAge = 0;

76

5. None of the options indicates a correct instruction. Question 42 Which of the options below gives a correct C++ instruction for line 12? 1. 2. 3. 4. 5. if (age != 0); if (age != 0) while (age != 0); while (age != 0) None of the options indicates a correct instruction.

Question 43 Which of the options below gives a correct C++ instruction for line 17? 1. 2. 3. 4. 5. cin >> average; average = total / nrSpectators; cin >> age; age += nrSpectators; None of the options indicates a correct instruction.

Question 44 Which of the options below gives a correct C++ instruction for line 19? 1. 2. 3. 4. 5. if (nrSpectators > 0) if (nrSpectators > 0); while (nrSpectators > 0) while (nrSpectators > 0); None of the options indicates a correct instruction.

Question 45 Which of the options below gives a correct C++ instruction for line 27? 1. 2. 3. 4. 5. cin >> average; cout << "No spectators"; cout << average << "No spectators" << endl; cout << average / nrSpectators; None of the options indicates a correct instruction.

77

COS111U/101/3/2009

ASSIGNMENT 2

SECOND SEMESTER

SUBMISSION: Printouts or electronically through myUnisa (in one file)


Please note that we automatically give nine days extension for Assignment 2. It will be to your own advantage to check whether the assignment has been registered on the system after a few days. If you want to submit the assignment electronically and myUnisa is off-line during that time, you need not contact us, because we will be aware of it. Simply submit it as soon as myUnisa is available again.

DUE DATE

11 September

EXTENSION

There is an automatic extension date namely 20 September. Do not phone or send e-mail. Study Guide, Lessons 1 - 22 70%

TUTORIAL MATTER WEIGHT OF CONTRIBUTION TO SEMESTER MARK NO unique number

IS YOUR SOFTWARE (both the compiler and the IDE) INSTALLED? Read Appendix 1 of this tutorial letter. Look at Troubleshooting under Using the software in file index.html on Disk 2009 or in Appendix 1 of this tutorial letter if your programs do not compile. If your output flashes on the screen and then disappears, you are storing the programs incorrectly. The names of the folders where the programs are stored should not contain space characters, for example My Documents is not permissible. Create a folder cos111 directly below c:\unisa and store your programs there (with names without space characters). PLEASE TURN OVER

78

QUESTION 1 In this question only short answers should be written down. Question 1a Suppose we want to input and validate three integers in a do..while loop. The variable names are n1, n2 and n3. The value of n1 may not be 13 and n2 has to be smaller than n3. If this condition does not hold, the loop has to be executed again. Write down a correct condition for the do..while loop. Question 1b Suppose we want to input and validate three characters in a do..while loop. The variable names are c1, c2 and c3. The requirement is that the values of c1 and c3 are not the same or that c2 is not equal to Z. If this condition does not hold, the loop has to be executed again. Write down a correct condition for the do..while loop. Question 1b Write down the output when the following fragment of a C++ program is executed: int n = 11; for (int i = 1; i <= 4; i++) n = n + i * 2; cout << n << endl; Question 1d Suppose Anna wants to buy a pair of shoes every month from June to December. Complete the for loop in the C++ program fragment below to calculate the total cost. float amount, totalAmount; cout << "What is the price of the first pair? "; cin >> amount; totalAmount = amount; for ( ; ; ) {

} cout << "Anna spent R" << totalAmount;

QUESTION 2:

NESTED LOOPS

Ms Angelina Barnard is the English teacher at Royden High. She shows the movie Gone with the wind to three separate groups of pupils. After each session every pupil who attended the show has to indicate whether he or she found Scarlett (indicated by S) or Rhett (indicated by R) or any other character (indicated by any character except S or R) the most interesting character in the movie. We need a C++ program to count the votes for each of the two main characters and the votes for all the other characters together. Then the three totals have to be displayed.

79

COS111U/101/3/2009

The program has the following structure: The three totals are initialised to 0. Now follows a for loop going from 1 to the number of sessions (namely 3). Inside the loop a prompting message is displayed asking the user to enter the number of pupils who attended the specific session. Inside this first for loop is another for loop. This loop goes from 1 to the number of pupils that attended the session. A prompting message appears asking the pupil for which character he or she wants to vote. Then the choice of the pupil is input. A switch statement inside the inner for loop is used to increment the correct total. The default option is used to count the votes for any other character than Rhett or Scarlett. When the outer for loop is exited, the three totals are displayed. In order to help you we give the following framework: #include <iostream> using namespace std; int main( ) { const int NR_SESSIONS = 3; int nrAttend; int votesForS, votesForR, votesForO; char choice; // initialise totals

// loop over the sessions for ( ; ; ) { // loop over attendants for ( ; ; ) {

} } cout << << cout << << cout << <<

"Votes for Scarlett: " votesForS << endl; "Votes for Rhett: " votesForR << endl; "Votes for another character: " votesForO << endl;

return 0; } Run your program with the input given below and submit printouts of the program and output. (We write the data of each session in one line, but you will possibly enter the values on separate lines.)

80

12 ASRSRRASRRSS 11 RRSSSAMLNSM 10 RSTAMRSTSS

QUESTION 3:

VALUE RETURNING FUNCTIONS WITH ONE OR MORE VALUE PARAMETERS

The IT firm ITEnterprizes has a unique way of deciding whether an applicant for a post should be invited for an interview or not. The decision depends on the candidates qualifications, age and years of experience and is made as follows: a certain weight is assigned to each of these aspects and the total is determined. All candidates with a rating above 44 are invited for an interview. You have to develop a C++ program to do the above. It will be done in three steps. You need to submit the program and output of question 3c only. You will see that we declare a global constant. Question 3a: Start small

We give the main function below. Your task is to write three functions, namely qualFactor, ageFactor and experFactor, all of return type int. Each of these functions has one value parameter. The function qualFactor receives a char value. The character U indicates a university degree and a weight of 40 should be returned. The character D indicates a diploma and a weight of 30 should be returned. The character M indicates that the candidate has passed Grade 12 at school and a weight of 20 should be returned. If any other character is received, a weight of 0 should be returned. Use a switch statement in this function. The function ageFactor receives an int value, namely the age. If the candidate is older than 22 but younger than 40, a weight of 10 should be returned. If the candidate is 40 years or older but not older than 55, a weight of 5 should be returned. A weight of 0 should be returned in all other cases.. The function experFactor receives an int value, namely the years experience. If the candidate has 10 or more years experience, a weight of 20 should be returned. If the candidate has less than 10 but more than 5 years experience, a weight of 10 should be returned. Otherwise a weight of 0 should be returned. Test your program with several input values but do not submit any printouts. // Assignment 2 Question 3a #include <iostream> using namespace std; // The required functions qualFactor, ageFactor and experFactor // should be inserted here. int main( ) { char qual; int age, exper, qualWeight, ageWeight, experWeight; cout << "Highest qualification" << endl << "Enter U (degree), or " << " D (diploma), or M (grade 10); otherwise any character: ";

81

COS111U/101/3/2009

cin >> qual; cout << "Age: "; cin >> age; cout << "Years experience: "; cin >> exper; qualWeight = qualFactor(qual); ageWeight = ageFactor(age); experWeight = experFactor(exper); cout << qualWeight << " " << ageWeight << " << experWeight << endl; return 0; } Question 3b: Still small "

Now write another value returning function, namely interviewOrNot, of return type bool. There are three value parameters. The function receives the three weights that were assigned to the qualification, age and years experience, respectively, and then has to determine whether the candidate should be invited to an interview. If so, the value true has to be returned. If not, the value false has to be returned. We give the main function again. Test your program with several input values but do not submit any printouts. // Assignment 2 Question 3b #include <iostream> using namespace std; const int CUT_OFF = 44; // The required functions qualFactor, ageFactor, // experFactor and interviewOrNot should be inserted here. int main( ) { char qual; int age, exper, qualWeight, ageWeight, experWeight; bool invite; cout << "Highest qualification" << endl << "Enter U (degree), or " << " D (diploma), or M (grade 10); otherwise any character: "; cin >> qual; cout << "Age: "; cin >> age; cout << "Years experience: "; cin >> exper; qualWeight = qualFactor(qual); ageWeight = ageFactor(age); experWeight = experFactor(exper);

82

invite = interviewOrNot(qualWeight, ageWeight, experWeight); if (invite) cout << "Candidate should be invited for an interview." << endl; else cout << "Candidate is unsuccessful." << endl; return 0; } Question 3c: Add a loop to the main function

Write a program containing the functions qualFactor, ageFactor, experFactor and interviewOrNot that you wrote in 3a and 3b. The program has to process a list of applications and display the applicable message for every application. You may use the main function of 3b but you will have to change it as it should now contain a for loop. Run your program on the list of 9 applications below and submit printouts of the program and output. U D M X U U M D D 26 26 26 33 66 44 38 44 36 4 5 8 13 40 2 20 20 12

QUESTION 4:

void FUNCTIONS WITH ONE OR MORE VALUE PARAMETERS

You need to submit printouts for question 4c only. Suppose we want to display the following figure containing the alphabetic character V on the screen: #^^^^^^^^^# ^#^^^^^^^#^ ^^#^^^^^#^^ ^^^#^^^#^^^ ^^^^#^#^^^^ ^^^^^#^^^^^ We want to be able to change the number of rows. In the figure above the number of rows is 6. If the number of rows is 4, the figure will look as follows: #^^^^^# ^#^^^#^ ^^#^#^^ ^^^#^^^

83

COS111U/101/3/2009

Question 4a:

One value parameter

Write a void function drawShape that displays such a figure on the screen. There should be one parameter (of type int), namely the number of rows as indicated above. Use the main function given below and input 5 as the number of rows. Make sure that the figure is correct but do not submit printouts of the program or output. Hint: Use for loops. Suppose nrP contains the number of rows. Then the i-th row should consist of (i - 1) ^ characters, followed by one # character, followed by (2 * nrP - 2 * i - 1) ^ characters, followed by another # character, followed by another (i - 1) ^ characters. The last row however, should contain only one # character. // Assignment 2 Question 4a #include <iostream> using namespace std; // The required function drawShape should be inserted here. int main( ) { int nr; cout << "Number of rows: "; cin >> nr; drawShape(nr); return 0; } Question 4b: Two value parameters

In 4a the # character formed the large V in the figure. Change function drawShape so that we are able to specify which character should form this large V. We give the new main function below. You will see that two values are now input in the main function, namely the number of rows and the character that should form the large V. Function drawShape should now have two parameters, one of type int (namely the number of rows) and one of type char (namely the character that should form the large V). Input 10 as the number of rows and @ as the character and make sure that the figure is correct but do not submit printouts of the program or output. // Assignment 2 Question 4b #include <iostream> using namespace std; // The required function drawShape should be inserted here. int main( ) { int nr; char charV; cout << "Number of rows: "; cin >> nr; cout << "Character for big V: ";

84

cin >> charV; drawShape(nr, charV); return 0; } Question 4c: Three value parameters

In 4a and 4b the ^ character filled the background of the figure. Change function drawShape so that we are able to specify what character should fill the background. The function drawShape will therefore have three value parameters, namely one of type int (the number of rows) and two of type char (the large V character and the background character, respectively). We do not give the main function again. You have to change both the main function and function drawShape. Run your program with 15 as the number of rows, % as the large V character and # as the background character. Submit printouts of the program and output.

QUESTION 5:

void FUNCTIONS WITH DIFFERENT TYPES AND NUMBERS OF PARAMETERS

Poppy is the manager of VeryVeryNiceCakes home industry that specialises in cakes. She gives two quotations to every customer that places an order: one for delivering and the other for pick-up by the customer. The quotations also depend on the sort of cake and the number of cakes. You have to write a C++ program to help Poppy with this. The program is developed in three steps. You have to submit printouts for 5c only. Question 5a: Two reference parameters

Write a void function inputAndValidate where the detail of one order are input and validated. The function should have two reference parameters, namely a parameter storing the sort of cake and a parameter storing the number of cakes. The sort has to be one of the following: chocolate, carrot, custard, fruit or coffee. This parameter is thus of type string. The second parameter is of type int. The first parameter has to be validated by using a do..while loop: the program should keep on displaying a prompting message until the user enters one of chocolate, carrot, custard, fruit or coffee. We give the main function below. Test your program to make sure that it works correctly but do not submit any printouts. // Assignment 2 Question 5a #include <iostream> #include <string> using namespace std; // The required function int main( ) { string sort; int number; inputAndValidate should be inserted here.

85

COS111U/101/3/2009

inputAndValidate(sort, number); cout << number << " " << sort << " cake(s). " << endl; return 0; } Question 5b: Two value parameters and two reference parameters

The amounts are calculated as follows: R80 for one fruit cake and R35 per cake for the other sorts of cake, R100 delivery fee for the complete order if fewer than 10 cakes are ordered, R8 per cake delivery fee if 10 or more cakes are ordered. Now write a void function calculateAmounts that calculates two amounts one amount that is due if the client should pick up the order at the shop and another amount that is due if the order should be delivered. This function has two value parameters supplying the sort of cake and the number of cakes to the function. Furthermore, there are two reference parameters, namely the two amounts that should be calculated and be available to the main function. We give the main function below. You will see that we declare several global constants. You should use them in the function that you write. Test your program but do not submit any printouts. // Assignment 2 Question 5b #include <iostream> #include <string> using namespace std; const const const const int int int int BASIC_PRICE FRUIT_PRICE DELIVER_1 = DELIVER_2 = = 35; = 80; 100; 8;

// The required functions inputAndValidate and calculateAmounts // should be inserted here. int main( ) { string sort; int number, amountSelf, amountDeliver; inputAndValidate(sort, number); calculateAmounts(sort, number, amountSelf, amountDeliver); cout << "If customer picks up the order: R " << amountSelf << endl; cout << "If order should be delivered: R " << amountDeliver << endl; return 0; }

86

Question 5c:

Final version

Declare another global constant NR_ORDERS and assign the value 7 to it. Now write a new main function containing a for loop going from 1 to NR_ORDERS. The two functions written in 5a and 5b should be called inside the loop and the two amounts should be displayed every time. Run your program on the data below and submit printouts of the program and output. chocolate 11 fruit 1 custart custard 8 carrot 10 coffee 6 coffee 2 chocolate 9

QUESTION 6:

FUNCTION CALLS

In this question you should write down short answers only. A function header is given and you have to write down a correct function call. You also have to declare all the variables that you use in the calling statement. Example: If the function header float price(string descriptionP) is given, a correct answer will be: float priceOfItem; string description; priceOfItem = price(description); Question 6a bool check(float amountP, char kindP) Question 6b int age(int yearP, string monthP) Question 6c void inputNames(string & firstP, string & secondP)

87

COS111U/101/3/2009

Question 6d void calcTwo(float amountP, float percP, float & monthP, & float yearP)

QUESTION 7:

DECIDE YOURSELF

Cecil and Belinda are the managers of a guest house with 22 rooms that can all be used as single or as double rooms. The tariff for a single room is R280. The tariff for a double room for two persons who share is R400. Breakfast is included in the price. Cecil and Belinda want a C++ program that they can run at the beginning of each week. The program should do the following for each of the seven days: input the booking (thus the number of single rooms and the number of double rooms) for that night. validate the booking if more than 22 rooms are booked, a message should be displayed that indicates that the booking is impermissible and repeatedly prompts the user to enter the two numbers again until the input is correct. display the number of persons that will have breakfast the next morning. display the income. Finally the total income for the week should be displayed. You have to write this program. The program should consist of five functions. Declare constants for the tariffs, the number of rooms in the guest house and the number of days. Main function: declare the following variables: int nrSingle, nrDouble, nrGuests; float income, totalIncome; and initialise totalIncome to 0. Use a for loop going from 1 to the number of days (namely 7). The other four functions have to be called inside the loop. When the loop has been exited, the total income should be displayed. Function inputInformation: This function involves the input. The specific booking, thus the number of single rooms and the number of double rooms, is input and checked that it is not more than 22 rooms in total. If the booking involves more than 22 rooms, a prompting message should be displayed and the two numbers have to be entered repeatedly until the total is no longer greater than 22. Decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Function numberForBreakfast: This function determines the number of guests for breakfast the next morning. Decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Function incomeOneNight: This function calculates the income from the specific booking. Decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide.

88

Function displayNumberAndAmount: This function displays the number of guests for breakfast and the income from the specific booking. Decide yourself on the type of function and the number and type(s) of the parameter(s). Follow the conventions of the Study Guide. Run your program on the data below where the first number represents the number of single rooms and the second number represents the number of double rooms. Submit printouts of the program and output.

4 8 9 5 0 17 7 15 5

6 12 2 14 18 10 10 15 15

89

COS111U/101/3/2009

ASSIGNMENT 3

SECOND SEMESTER

Submission: The assignment should NOT be submitted.


You should assess it yourself when you receive the model solution. Note that there will be examination questions set on this part of the Study Guide also.

DUE DATE EXTENSION TUTORIAL MATTER

19 October Not applicable Study Guide, Lessons 1 to 29. Note that Lesson 30 is not examination material. It is meant for enrichment. 0%

WEIGHT OF CONTRIBUTION TO SEMESTER MARK NO unique number QUESTION 1: VARIABLE DIAGRAMS REVISITED

Draw a series of variable diagrams for the program below. Use the conventions of the Study Guide. Compare your answers to the model solution. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // variable diagrams revisited #include <iostream> using namespace std; const int AA = 300; int func1(int n, int n1) { n -= 3; n1 += n; return 2 * n * n1 + AA; } void func2(int n, int & n1) { n = 2 * AA; n1 = n n1; } void func3(int & n, int & n1) { int k; k = n1 * 3; n = k + 30; n1 = k + 2 * n;

90

22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

} int main( ) { int n, m, j; n = 5; m = 10; j = func1(n, m); n = 15; m = 20; func2(n, m); n = 25; m = 30; func3(n, m); return 0; }

QUESTION 2:

ONE-DIMENSIONAL ARRAYS

We have to write a program to display the names of soccer players who received more (yellow or red) cards than the number of goals scored by them. The names of the players are given but the number of goals scored and the number of cards received by each player have to be input. Declare a global constant, namely NR_PLAYERS, and set it equal to 12. The program should consist of four functions. No global variables may be used. The main function: Declare the following four one-dimensional arrays: names of type string where the 12 names (see below) will be stored, goals of type int where the number of goals scored by the players will be input, cards of type int where the number of cards received by the players will be input, namesMore of type string where the names of the players with more cards than goals will be stored. The array names should be initialised in its declaration. The strings to be stored are: "Tiny Nakedi", "Cecil Mametsa", "Chris Rooney", "Mario Thomas", "Frank Ntini", "Charlie Ashley", "Morio Zondo", "Khabo Mosimane", "Pitso Hack", "Lloyd Mokoena", "Rick Smith", "Kabelo Ramago". The main function has to call the other three functions one after the other. We give the type of everyone of the other functions but you have to decide yourself on the number and type(s) of the parameter(s). Use the conventions of the Study Guide. The void function inputInformation: The information about goals and cards are input here. The function should contain a for loop. Every time that the loop is executed, the name of a player should be displayed and then the number of goals scored and the number of cards received by that player have to be entered.. The void function findPlayersWithMoreCardsThanGoals:

91

COS111U/101/3/2009

The function should contain a for loop. Every time that the loop is executed, the number of cards and the number of goals of the relevant player should be compared. If the number of cards is greater than the number of goals, the name of the player should be stored in a separate array. (Thus the name of the first player with more cards than goals is placed in the first element of this new array, the name of the second player with more cards than goals is placed in the second element of the new array, et cetera.) The function should also determine the number of players whose names appear in this array and should make it available to the main function. The void function displayInfo: The function has to display the names of all players with more cards than goals. Run your program on the data below. The first number is the number of goals scored by the player and the second number is the number of cards that the player received. The data is in the same order as the names listed above. Compare your output to that of the model solution. 4 0 0 1 2 1 1 2 2 2 4 5 2 0 3 2 2 3 0 4 1 2 5 6

QUESTION 3: TWO-DIMENSIONAL ARRAYS Four friends, Aggie, Bruce, Cecil and Danita, are registered for the three modules ABC111, DEF222 and GHI333. The number of hours each of them spends weekly on his or her studies are given in the following table: ABC111 11 9 8 12 DEF222 9 10 8 8 GHI333 7 13 8 9

Aggie Bruce Cecil Danita

Write a program consisting of a main function and three other functions. The main function has to call the other three functions. You are not allowed to use any global variables but you should declare two global constants, namely NR_FRIENDS and NR_MODULES. The program should do the following: Input the various numbers of hours row by row and store it in a two-dimensional array with four rows and three columns. The values should be input in the void function inputHours. Compute the total study hours of each friend and then display the smallest of these four totals. All the computations should be done in the int function hoursLeast. The smallest total should be returned to the main function and displayed there.

92

Display the average number of hours spent on each module. The computation of the averages should be done in the void function displayAverages and they should also be displayed there.

Run your program on the data and compare your output to that of the model solution.

QUESTION 4:

STRINGS DELETE AND INSERT

Write a program consisting of a main function and one other function. A string should be input in the main function and then the string function changedString should be called. The function should do the following: Delete every odd occurrence of t. Thus delete the first, third, fifth, etc occurrence of t in the given string. Insert h after every even occurrence of t. Thus insert h after the second, fourth, sixth, etc occurrence of t in the original string. Suppose the string The cats and the rats teeth will stop any tortoise. is input. Then the following string should be returned to the main function: The cas and thhe ras theeh will sthop any orthoise. No global variables may be used. Use a while loop in the main function and execute the loop until NOTHING MORE is input. Run the program on the strings below and compare your output to that of the model solution. This is not the first time that this has happened, or is it? Katte en tarentale rym met latte en liniale. It is a pity that Kitty is very pretty. There is the thing I want. Lettie thinks the theory is true. NOTHING MORE

QUESTION 5:

MORE STRINGS

In this question you have to write a program consisting of three functions. A string has to be input in the main function. If the string has odd length, a string function doubledString should be called to double the string. Thus, if the string was Ben, it should be changed to BenBen. (The string will now be of even length.) Then another string function, namely expandedString, should repeatedly be called to expand the string. This is done by inserting the central two characters into the centre of the string. If, for example, the string is 123456, it will be 12334456 after the first call of expandedString, it will be 1233344456 after the second call of expandedString, it will be 123333444456 after the third call of expandedString, et cetera. Main function: Use a for loop to process six strings. Inside the loop a string has to be input. If the length of the string is an odd number, the string function doubledString should be called. After this call the string will be of even length. Then the string function expandedString has to be called repeatedly until the string becomes longer than 40 characters.

93

COS111U/101/3/2009

Function doubledString: The function receives a string and returns the doubled string. If, for example, the string qwertyu is received, qwertyuqwertyu should be returned. Function expandedString: The function receives a string of even length and expands it by inserting the two central characters into the centre of the string. If, for example, the function receives the string Hi Johnie! the string Hi Joohhnie! should be returned. No global variables may be used. Run your program on the strings below and compare your output to that of the model solution. Cheers! String manipulation is easy. Only two questions remain to be done. Hier gaan ons al weer. Can you believe it? !@#$%^&*

QUESTION 6:

GARDEN SERVICES

FloraServices is n firm that services gardens. They work once a week for three hours in the garden of each of their customers. The following information is available for each of the gardens currently serviced by them: address (a string, for example 44 Main Street) day of the week on which the specific garden is serviced (a string, for example Monday) number of gardeners working together in the specific garden (an integer, for example 4) an indication whether there is a swimming pool in the garden (a character, namely Y if there is a pool, and N if not). You have to write a program to provide the management with certain information. Question 6a: Declare a struct

Write down the declaration of a struct for storing the information about a single garden. Give the name GardenInfo to the struct. Question 6b: An array of structs

Write down the declaration of a constant NR_OF_GARDENS and set it equal to 12. Then write down the declaration of an array of 12 structs that will contain the information about 12 gardens.

94

Question 6c:

A function to input the information

Write a function inputInformation that inputs the information about 12 gardens. The function header should be void inputInformation(GardenInfo gardensP[]) Use a do..while loop to validate the input about the presence of a swimming pool, thus a prompting message should appear, repeatedly asking that either Y or N be entered until it is done. Question 6d: A function to display specific information

Write a function displaySomeInformation to display the following three groups of information: (i) the addresses of all gardens serviced on Tuesdays, (ii) for all gardens in Long street that have pools, the days on which they are serviced and the number of gardeners working there, (iii) the addresses of all gardens requiring more than 4 gardeners at a time. The function header should be void displaySomeInformation(const GardenInfo gardensP[]) Question 6e: A complete program

Write a main function that calls the other functions. Use the declarations and functions above to form a complete program. No global variables may be used. Run your program on the data below and compare your output to that of the model solution. 33 Mandela street Manfred House 123 Long street 5 Oak Avenue 555 Long street 999 Long street 2 Main street Kiepersol Park 456 Long street Central Square Flora Park 50 Long street Monday Friday Tuesday Tuesday Thursday Wednesday Tuesday Monday Wednesday Monday Thursday Friday 3 6 3 4 2 6 1 7 2 7 5 3 Y Y Y N N Y N N Y N N Y

95

COS111U/101/3/2009

Appendix 1:

INSTALLING AND USING THE SOFTWARE

(This information is also given on Disk 2009.)

1. Software for COS111U


The first level C++ programming modules in Computer Science (COS111U and COS112V) both use the same prescribed software; in particular, a C++ compiler and an Integrated Development Environment (IDE). The compiler you will be using for these modules is the MinGW port (version 5.0.0) of the Gnu Compiler Collection (version 3.4.2). The MinGW compiler is designed to work on Windows 95/98/NT/2000 platforms. Please note that Windows Vista is still an unstable operating system, and we can make no guarantee that the MinGW compiler will work with it. If you want to try to use MinGW with Windows Vista, you will probably have to ask the vendor who supplied you with Windows Vista to adjust the security settings to get it to work. The MinGW compiler is distibuted under the GNU Public Licence, which means you are free to use, copy, sell or modify the MinGW compiler and you are not required to register or pay for any of this software. (More information on MinGW can be found at http://www.mingw.org/). To access the compiler, you will be using an Integrated Development Environment called Dev-C++ (version 4.9.8.3). Neither the creators of Dev-C++, nor ourselves, require you to pay for it or register it. (See http://www.bloodshed.net/ if you want more information). Please note that you will probably also have problems installing and running Dev-C++ under Windows Vista. We will not be able to assist you if you attempt to use the prescribed software with Windows Vista. Apart from the compiler and IDE, we have included other useful software and documentation on the CD-Rom. General purpose utility software (WinZip, Adobe Reader etc.) is in the \utils folder. Extra programming software, IDEs, sources etc. are in the \src folder. The Dev-C++ help system contains help for Dev-C++. We have added links to general C++ help. There is also some additional documentation in the \docs folder of the CD-Rom. We are indebted Bjarne Stroustrup for a number of his publications on C++. We also thank all of the many contributors to all of the open source software on the CD-Rom.

2. Installing the software


You need to install the MinGW compiler and the Dev-C++ IDE. This section gives two methods for doing so. Method 1 Insert the CD into the CD drive and navigate to the CD drive using "Windows Explorer". Double click on "Index.html" and then click on the second left-hand link COS111-U. Then click on the link on the left-hand side called 2. Installing the software. To install the MinGW compiler, follow the blue link here in the sentence To install the MinGW compiler, click here. by clicking on it. A window will appear containing an icon for the MinGW setup called mingw_gcc3.4.2.exe. Double-click the file/icon and follow the instructions after that.

96

During installation, you will be asked to choose the Destination Directory where the compiler must be installed. We recommend that you accept the default destination directory, namely c:\unisa\mingw. If you choose anything else, you will have to fix the installation by changing the Compiler Options of Dev-C++. To install the Dev-C++ IDE: Follow the blue link here in the sentence To install the Dev-C++ IDE, click here. by clicking on it. A window will appear containing an icon for the Dev-C++ setup. Double-click the icon and follow the instructions after that. During the installation, you will be asked to specify the Destination Directory where you want Dev-C++ to be installed. We recommend that you choose the default, namely c:\unisa\devcpp. Method 2 First install the MinGW compiler: Double-click on the "My Computer" icon on your desktop Right-click on your CD-Rom icon, and select "Explore" Navigate to the \install\mingw folder Double-click on the file mingw_gcc3.4.2.exe During installation, you will be asked to choose the Destination Directory where the compiler must be installed. We recommend that you accept the default destination directory, namely c:\unisa\mingw. Then install the Dev-C++ IDE:

Navigate to the \install\devcpp folder Double-click on the file devcppsetup.exe

During the installation, you will be asked to specify the Destination Directory where you want Dev-C++ to be installed. We recommend that you choose the default, namely c:\unisa\devcpp. Uninstalling To uninstall either the compiler or the IDE, use the "Add/Remove Programs" facility in the "Control Panel" of Windows. If you want to uninstall and then re-install the software, you should do the above for both the compiler and the IDE. Then search for the hidden devcpp.ini files (there should be two), delete them and install Dev-C++ again.

97

COS111U/101/3/2009

3. Using the software


Dev-C++ provides a friendly user interface to the MinGW C++ compiler. In fact, it will not be necessary for you to work directly with the compiler. You can always do so by means of Dev-C++. In COS111U, the programs you write will be somewhat simpler than for COS112V. In particular, all the programs will consist of a single file, so you can get by without a project. To help you get started we present a short guide to your first "Hello World" program. Step 1. Starting Dev-C++ During installation, a shortcut to Dev-C++ should have been placed on the desktop. Double-click it to start DevC++. Otherwise, you can click on the Windows "Start" button and choose "Bloodshed Dev-C++" on the "Programs" submenu. Alternatively, you can navigate to the folder C:\unisa\devcpp and execute the file devcpp.exe Step 2. Setting the options The first time you use Dev-C++, you will be required to choose the language and the user interface theme. We suggest that you click on OK for each of these options to accept the defaults. Before you use Dev-C++ to write your first program, you MUST change some of the settings to get it to work properly:

Choose "Compiler Options" on the "Tools" menu and click on the "Directories" tab. Under the "Binaries" subtab, the path C:\unisa\mingw\bin should appear. If there is some other path specified, click on the "Delete Invalid" button. Either type the correct path in the edit box at the bottom of the window, or choose it by clicking on on the "..." browse button. Then click on the "Add" button to transfer the path from the edit box to the list under "Binaries". Under the "Libraries" subtab, the path C:\unisa\mingw\lib should appear. If it isn't there, follow the above instructions to fix it. Under the "C Includes" subtab, the path C:\unisa\mingw\include should appear. If it isn't there, follow the above instructions to fix it. Under the "C++ Includes" subtab, no paths should appear. If any are listed, click on the "Delete Invalid" button. Finally, click on the "Programs" tab (at the top of the window). Change the program for "make:" to mingw32-make.exe. (It must not be gmake.exe.)

You only need to perform the above steps once. You are now ready to write your first C++ program! Step 3. Creating a new C++ source file To create a source file, choose "New | Source File" on the "File" menu or click on the "Source File" toolbar button. An empty source file will be displayed in the edit panel:

98

Step 4. Editing the source file Type in the following program in the edit panel:

The source file is still called Untitled1, so you should give it a name. Do this by choosing "Save" or "Save As" on the "File" menu or by clicking on the "Save" toolbar button. We suggest that you create a separate directory (such as C:\unisa\cos111) in which you save all your work for a particular module. Beware: Do NOT save it in a directory

99

COS111U/101/3/2009

(or a path) with a space in it (such as C:\My Documents\cos111). Navigate to the directory you've created (if necessary) before typing the name of the source code file, eg. first.cpp and clicking on the "Save" button. By the way, you can hide the Project/Class browser (the panel on the left) by deselecting "Project/Class Browser" on the "View" menu. You won't be needing this for COS111U. Step 5. Compiling the program This is the easy part. Choose "Compile" on the "Execute" menu or click on the "Compile" toolbar button. A Compile Progress dialog will be displayed:

When the Status is Done and the "Cancel" button changes to "Close", click on the "Close" button. Assuming you haven't made any typing mistakes, your program should compile without any errors. (If there are errors, a Compiler Output panel will be displayed below the code editor specifying the errors that need to be fixed.) If you are SURE that you have typed in the program precisely correctly, but an error message is displayed every time you compile the program, see Troubleshooting below. Step 6. Running the program This is the fun part. To see the fruits of your labour, either choose "Run" from the "Execute" menu or simply click on the "Run" toolbar button. If all goes well you should see a window like this:

100

If you don't see this console window because it flashes and disappears, choose "Environment Options" on the "Tools" menu and make sure "Console Window Remains Open" (on the "General" tab) is selected. Then run the program again. Make sure that your source code file is not saved in a directory (or a path) with a space in it. We recommend that you create a directory called C:\unisa\cos111 and save all your source code files there. Press any key to close the console window. Congratulations! You have just compiled and run a C++ program using MinGW and Dev-C++. Easy, wasn't it? To create a new program, close your existing program, and open a new one. To edit an existing program (one that you worked on previously), choose "Open Project or File" on the "File" menu or click on the "Open Project or File" toolbar button. Troubleshooting It is possible that Dev-C++ doesn't know where the MinGW compiler is. Check the following in "Tools | Compiler Options" under the "Directories" tab: C:\unisa\mingw\bin should be added to "Binaries". C:\unisa\mingw\lib should be added to "Libraries". C:\unisa\mingw\include should be added to "C Includes". "C++ Includes" should be empty. Note that if you installed the MinGW compiler in a directory other than the default (i.e. not in C:\unisa\mingw) then you will have to change these paths accordingly.

101

COS111U/101/3/2009

If your program compiles correctly but when you run it the (black) console window just flashes briefly, go to "Tools | Environment Options" and make sure the option "Console Window Remains Open" is checked. If the above doesn't solve the problem, make sure that your source code file is not saved in a directory (or a path) with a space in it. We recommend that you create a directory called C:\unisa\cos111 and save all your source code files there.

4. Printing
To print a C++ program, choose the "Print" option on the "File" menu of Dev-C++ or click on the "Print" toolbar button. (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 textbased 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: Click on the Mark (first) button (after the Font drop-down list) on the toolbar of the console window. Hold the Shift key down and use the arrow keys to mark (highlight) the text as a block. Click on the Copy (second) button 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: 1. Run your program, and when it has finished executing (and you are happy with the output) close the console window. 2. 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\cos111.) 3. 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. 4. Make sure that your printer is switched on, is "On-line" and has paper in it, etc. 5. Press <Ctrl+P> to ensure that all the output generated from now on is sent to the printer. 6. Type the name of the executable file, eg. first.exe and press <Enter> to run your program again. 7. Enter any values that the program requires as input. 8. 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. 9. Now you can close the console window.

102

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

Appendix 2:

VISTA

Please note that we do not support Vista, but you are welcome to use the information below. How to install the software on Vista: 1. Install mingw and devcpp as instructed on DISK 2009 (and in Appendix 1 of this tutorial letter). 2. Run the compatibility wizard by doing the following: 2.1 Click on Start 2.2 Choose Control Panel 2.3 Type compatibility in the Search block (top right of Control Panel window) 2.4 Click on Use an older program with this version of Windows under Default Programs as shown below:

2.5 2.6 2.7

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

103

COS111U/101/3/2009

2.8 2.9 2.10 2.11 2.12

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

2.13 2.14 2.15

Click on Next Choose No in the following window and then click on Next Click Finish in the next window to complete the Program Compatibility Wizard.

104

3.

Now you need to create a shortcut to Devcpp. To set up the shortcut to DevCpp follow the steps below: 3.1 Click on Start
3.2 3.3 3.4 3.5 3.6 Choose Computer Double-click on C: Double-click on unisa Double-click on devcpp Select devcpp application as shown in the window below

3.7

Right-click on devcpp application, choose Send To in the pop-up menu and then Desktop (Create shortcut) as shown below.

105

COS111U/101/3/2009

This will place the following shortcut on the desktop:

3.8

Double-click on the shortcut to activate devcpp.

Appendix 3:

BUYING A COMPUTER SYSTEM

Appendix 3.1 WHAT MODEL SHOULD I GET? There are many different computer models available and the starting point is to consider what CPU the computer should have. After that, one should consider the memory, the disks and the screen. These items comprise the computer hardware. We also describe what software a new computer will need. Appendix 3.2 THE CPU The CPU is the brain of the computer. If you are buying a new computer, you should get at least a Pentium IV. If you are buying a second-hand computer, you should buy a Pentium I, II or III only if you can get them at a price much lower than that of a new computer. Appendix 3.3 THE MEMORY A computers memory is measured in terms of bytes. The computer you get should have at least 16 MB of memory, although more would be preferable. (This type of memory is usually called RAM.) Appendix 3.4 THE DISKS Computers have fixed disks and removable disks. Fixed disks are also called hard disks. The computer that you use should have at least a hard disk and a CD-Rom drive. A hard disk (or fixed disk) is a fixed part of the computer and does not come out. The hard disk on any computer you buy should be at least 500 MB, but preferably larger. Nowadays many of the powerful software packages (such as Windows) come on a CD-Rom (which looks just like a music CD). The C++ compiler that you will be using for COS111U has been provided on the CD-Rom disk that you should have received with your study package. A hex speed drive (or 6x) CD-Rom drive is ample for Unisa modules, although new computers usually have at least a 12x or 16x drive. On its own, a CD-Rom does not allow you to play sound on a computer out loud. So if you want full multimedia, you will need an appropriate sound card and loudspeakers. (This is, however, not needed for any of our modules.) Appendix 3.5 THE SCREEN With the usual desktop computer, it is best to have a screen that measures 14 inches or more on the diagonal. New computers come with VGA or Super VGA display cards and these are fine for our use

106

Appendix 3.6 THE PRINTER To get a paper version of your programs, you will need a simple printer. The most reasonably priced printers are inkjet printers, and these are fine for the purposes of your studies. Laser printers give the best output, but are usually more expensive. Appendix 3.7 THE SOFTWARE The items we discussed above make up the computer hardware. However, before you can use a computer, you also need software. For this module you will need two software packages, namely the operating system and the C++ compiler. New computers should come with an operating system such as Windows 95, Windows 98, Windows 2000, Windows NT, or Windows XP installed. Windows 95 is sufficient for this module, but later versions of Windows are also fine. At this stage, however, it seems that Vista is not compatible with our software and we do not support it. However, see Appendix 2 if you want to try to use the software with Vista as operating system. You will also need a browser program to view the instructions for installing the software supplied on the CD-Rom. (Section 8.2 of this tutorial letter explains how to view these instructions with the browser.) All computers with Windows 95 or later come with a browser called Internet Explorer. Please note that it is not necessary to have an Internet connection for this. The browser software is necessary to view documents on the CD-Rom disk, and not necessarily to surf the Internet! The software you need for all the programming tasks for this module is a C++ compiler. This is included on the CDRom that you should have received together with your study package. As mentioned above, this CD-Rom disk (Disk 2009) contains instructions on how to install the software and use it. (The instructions are repeated in Appendix 1 of this tutorial letter.) See Section 8.2 of this tutorial letter on how to reach the relevant file.) If you do not receive Disk 2009 upon registration, you should download the software immediately from the Internet so that you are able to start with your studies at once. See Section 3 of this tutorial letter. The lecturers will answer queries about the installation of the software until 31 January (first semester) and 25 July (second semester). From 1 February and 26 July, respectively, no such problems will be discussed.

107

COS111U/101/3/2009

Appendix 4

SCIENCE FOUNDATION PROGRAMME

WHAT IS FOUNDATION PROVISION? Foundation provision is an extended additional teaching and learning intervention whose primary purpose is that of improving the success and graduation rate of identified at-risk students. Because Unisa is a higher education distance learning institution the extended additional teaching and learning intervention will include: the appointment of science specific tutors to assist the at-risk student supporting at-risk students with academic learning gaps arranging peer collaborative learning opportunities with fellow students on regional level. WHAT IS THE SCIENCE FOUNDATION PROGRAMME (SFP)? The SFP runs concurrently with normal science teaching and learning activities. It creates more opportunities for students to be exposed to the learning content and activities. For 2008- 2010 the extended additional teaching and learning intervention will be limited to science students who register in the College for Science, Engineering and technology and the College for Agriculture and Environmental Sciences in their first year. The foundation provision will be available for students registered for this module WHO CAN PARTICIPATE IN THE SFP? All new science students to Unisa adhering to specific SFP admission criteria are allowed into the SFP. Selection criteria that will identify at-risk students are determined taking into account the students M-count total, marks in school mathematics, Physical sciences (and/or Biology Physiology etc.) and language subjects. A post registration diagnostic test will further inform at-risk student of any academic literacy gaps. More information will be send to you at a later stage. HOW DOES A STUDENT GAIN ADMISSION TO THE SFP? Once a student has been identified as at risk, she/he will automatically qualify for the SFP. Such students will be contacted by either the regional academic manager/coordinator or SFP tutor to inform the student of additional tutoring classes, peer group learning classes or academic literacy sessions (Consult the Services and Procedures brochures for more information). These interventions will be provided at no additional cost. WILL PARTICIPATION IN THE SFP PROVE TO BE SUCCESSFUL? Given the extended and additional learning opportunities created by the SFP it is envisaged that the success rate of at-risk students will be increased. Much of the success will be determined by the students willingness to spend additional time and effort to attend the tutoring classes, academic literacy sessions and peer collaborative learning opportunities.

UNISA 2008

You might also like