Sie sind auf Seite 1von 20

COS1512/201/1/2019

Tutorial letter 201/1/2019


Introduction to Programming II

COS1512
School of Computing
This tutorial letter contains the
solutions to Assignment 1
COS1512/201/1/2019

INTRODUCTION

By the time you receive this tutorial letter you should have already completed assignment 1 and we
hope that you are well on your way with your studies. This tutorial letter contains the solutions to
Assignment 1. You are welcome to e-mail me with any queries at schoema@unisa.ac.za. Also take
note of the following telephone number and the days on which the lecturer are available in case you
have to call.

Mondays Dr MA Schoeman 011 670 9178


Tuesdays Dr MA Schoeman 011 670 9178

Allocation of marks
When we mark assignments, we comment on your answers. Many students make the same mistakes
and consequently we discuss general problems in the tutorial letters. It is, therefore, important to work
through the tutorial letters and to make sure you understand our solutions and where you went wrong.
The maximum number of marks you could obtain for Assignment 1 is 55. This is converted to a
percentage. If you for instance obtained 35 marks for Assignment 1, you received 40/55 * 100 = 73%
for Assignment 1. This percentage in turn contributes a weight of 20% to the year mark, as can be seen
in the summary of the weights allocated to the assignments for COS1512 below.

Assignment
Weight
number
1 20
2 80
3 0

We give the mark allocation for the questions below. For questions 1 – 4 you will not get any marks if
you did not include the program code. Or if you only included part of the code, you will get a maximum
of 2 marks if the included code is correct. Please note that this is NOT the way exam answers will be
marked. If you did not include the output for your program, you will not get full marks for the question.
We discuss a possible solution for each question below. Please read through the solution and
discussions thoroughly.

The marks you received for question 1 was determined on the following basis:
Question not done 0/5
Question attempted, but the program does not work at all 2/5
A good attempt, but there are a few problems with your answer 4/5
The program works correctly and produces the correct output 5/5

The marks you received for question 2 was determined on the following basis:
Question not done 0/5
Question attempted, but the program does not work at all 2/5
A good attempt, but there are a few problems with your answer 4/5
The program works correctly and produces the correct output 5/5

2
COS1512/201/1/2019

The marks you received for question 3 was determined on the following basis:
Question not done 0/8
Question attempted, but the program does not work at all 2/8
A good attempt, but there are a few problems with your answer 5/8
The program works correctly and produces the correct output 8/8

The marks you received for question 4 was determined on the following basis:
This question was not marked. If you attempted the question and produced the correct output, you will
get 5 marks. If you attempted the question, but did not show the correct output, you will get 3 marks. If
you did not attempt the question, you will get 0 marks. Please go through the solution that we give for
question 4 to make sure that you understand how to work with text files.

The marks you received for question 5 was determined on the following basis:
One mark each for question 5(a) – (k), 5(l)(i) - 5(l)(xiv), and 5(m)(i)-5(l)(vi).
Total number of marks for question 5 is max 32 marks.

Question 1 5 marks

For this question you had to write a program to use two overloaded functions, each named
calcCharges(), to calculate the charges for a patient’s hospital stay. The charges for inpatients are
calculated based on the number of days sent in hospital, the daily rate, the hospital medication charges
and the charges for hospital services such as lab tests etc. The charges for outpatients are calculated
based on the hospital medication charges and the charges for hospital services such as lab tests etc.
Overloaded functions need to differ in either the number of parameters and/or the type of parameters
supplied to the functions. In this question you had to write an overloaded function (calcCharges() ) with
either two or four parameters of type double. The question did not clearly state whether the respective
charges should be input by the user. We have asked the user to input all the charges.

#include <iostream>
using namespace std;
// overloaded function for in-patient charges
// Pre: nr of days in hospital x daily rate + medication + service
// charges
// Post: returned value is total charge
double calcCharges (int days, double rate;
double medCharge, double servCharge);
// overloaded function for out-patient charges
// Pre: medication + service charges
// Post: returned value is total charge
double calcCharges (double medCharge, double servCharge);

int main()
{
char answer;
int nrDays = 0;
double dailyRate = 0.00,
medicationCharge = 0,
serviceCharge = 0,
totalCharges = 0;
cout << "Welcome to the calculate patient charges program"
<< endl << endl;

3
COS1512/201/1/2019

cout << "Was the patient admitted as an in-patient or an out-patient: "


<< "i or o: " << endl;
cin >> answer;
if ((answer == 'i') || (answer == 'I'))
{
cout << "How many days were spent in hospital? : ";
cin >> nrDays;
cout << "What is the daily rate? : ";
cin >> dailyRate;
cout << "What is the hospital medication charges? : ";
cin >> medicationCharge;
cout << "What is the service Charges? : ";
cin >> serviceCharge;
totalCharges = calcCharges(nrDays, dailyRate,
medicationCharge, serviceCharge);
}
else
{
cout << "What is the hospital medication charges? : ";
cin >> medicationCharge;
cout << "What is the service Charges? : ";
cin >> serviceCharge;
totalCharges = calcCharges(medicationCharge, serviceCharge);
}
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << endl << "The total charges for this patient is : R"
<< totalCharges =<< endl;
return 0;
} The overloaded
functions have the
//overloaded function for in-patients same function
double calcCharges (int days, double rate;
double medCharge, double servCharge) name
{ CalcCharges().
return (days * rate + medCharge+ servCharge); The difference is
} the number of
parameters in
//overloaded function for out-patients these functions.
double calcCharges (double medCharge, double servCharge)
{ The compiler will
return (medCharge+ servCharge); use the number of
} parameters to
decide which
function to call.

4
COS1512/201/1/2019

Input and corresponding output version 1:

Input and corresponding output version 2:

Question 2 5 marks

Discussion:
For this question, you had to write a program to determine whether a student qualifies to register for the
BSc Computer Science degree. A student qualifies if he or she is has achieved a minimum of 60% in
Mathematics, Physical Science and English. The program should use the assert function to validate that
the marks of the students are not more than 100%. The program should then display a message to
inform the student whether he qualifies or not. You had to run your program twice, once to test it with
marks for Mathematics, Physical Science and English less than or equal to 100%; and the second time
testing it with one of the marks for Mathematics, Physical Science and English more than 100%.

The assert() function evaluates a boolean expression. If the result is 1 (true), the program continues. If
the result is 0, the program aborts with an exception. You did not have to handle the exception in your
program. We just wanted to see that you did get the exception in your output, when the conditions were
not met. To use the assert() function in your program, you must include the cassert header file in your
program:
#include <cassert>

We ran the program three times, twice with valid marks, and once with invalid marks.

5
COS1512/201/1/2019

Program listing:

//Ass1 question 2
#include <iostream>
#include <iomanip> The assert function is
#include <cassert> used in this section. The
using namespace std; assert function will
check if the input meets
int main() the criteria. The input in
{ this case are
double dblPhysics; dblPhysics,
double dblEnglish; dblMaths and
double dblMaths; dblEnglish
cout << "Marks for Physical Science: " << endl; intYrBirth. If it meets
cin >> dblPhysics; the criteria, the program
cout << "Marks for Mathematics: " << endl; will continue. If
cin >> dblMaths; the criteria are not met,
cout << "Marks for English" << endl; the assert function will
cin >> dblEnglish; throw an exception error.
The criteria are
assert ((dblPhysics <= 100) && (dblMaths <= 100) &&that the intYrBirth
(dblEnglish <=
100)); should
{ not equal the current year
and it
if(dblPhysics >= 60 && dblMaths >= 60 && dblEnglish>=60)
{ must not be greater than
the <<endl;
cout<<"You qualify for Bsc Computer Science"
} current year.
else
{
cout << "You don't qualify for Bsc Computer Science "<< endl;
}
}
return 0;
}

Input and corresponding output 1:

6
COS1512/201/1/2019

Input and corresponding output 2:

Question 3 8 marks

Discussion:
In this question, you had to write a C++ program that the Traffic Department can use when the owner
of a car pays all his outstanding road fines. The Traffic Department has a file called Fines.dat that keeps
the registration number and the road fine due for each traffic offence, one per line. Your program should
have requested the registration number from the user, read the contents of file Fines.dat line by line; if
the road fine matched the registration number, displayed the fine and calculated the total amount due
for that registration number. At the same time all the remaining registration numbers and road fines
should have been written to a new file called OutStandingFines.dat.

The first step is to create the input file. We created the input file Fines.dat by using the Code::Blocks
editor and creating a new source file, entering the data, and saving it as a file with an extension of .dat.
See Tutorial Letter 101 for the data you should have used to create Fines.dat. You could also have used
Notepad. Save your input file in the same directory as your program.

The purpose of the program is to read the file, manipulate data (by comparing registration numbers, and
calculating the fine due if necessary) and display output on the console. It should also create a new data
file containing the remaining outstanding fines (OutstandingFines.dat). Therefore the header file for the
fstream library have to be added to the code with the #include <fstream> directive.

We read the input file by opening a file called Fines.dat and associating the file names with the
ifstream variables, as shown in the statements below:

ifstream in_stream;
in_stream.open("Fines.dat");

Note that if you create the input file in a directory different from the one where you save your program,
you need to specify the path as well, when specifying the filename, e.g.
C:\COS1512\datafiles\Fines.dat

When using a file it is essential to test whether the file is available. The following code segment tests
whether the first input file is available before attempting to extract from it:
if(in_stream.fail())

7
COS1512/201/1/2019

{
cout << "Failed to open a file" << endl;
exit(1);
}

Note that it can also be done as follows:


if (!in_stream)
{
cout << "Failed to open a file" << endl;
exit(1);
}

In the above code segment the program is terminated immediately when exit(1) is invoked. We
need to add #include <cstdlib> to our program i.e. the header file for the library that contains
this function.

Remember to close the input file.


in_stream.close();
One gets input from a file into your program,
Program listing: or send output to a file from your program by
#Assignment 1 Question 3 using streams, or special objects as they are
#include <cstdlib> called in C++. The type for input-variable
#include <iostream> streams is named ifstream, and for output-
#include <fstream> variable streams, ofstream.
One connects the object to the file by
using namespace std; opening the file, as is done in the code. We
include the fstream header file as well.
int main() Please see section 6.1 of Savitch for more
{ information.
double totalFines = 0;
double fine;
string regNr, rNr;
ifstream in_stream; One should always check
in_stream.open("Fines.dat"); whether a file has been
opened or closed
if(in_stream.fail()) successfully. The member
{ function fail() does
cout << "Failed to open a file" << endl; exactly that. It returns a
exit(1); Boolean value of false if
} the file opened/closed
ofstream out_stream; successfully, and allows the
program to continue. Please
out_stream.open("OutStandingFines.dat"); read section 6.1 in Savitch
if(out_stream.fail()) for further information.
{
cout << "Failed to open a file" << endl;
exit(1);
}

cout << "Please enter registration number:";


cin >> regNr;
cout << "Fines:" << endl;
cout.setf(ios::fixed);

8
COS1512/201/1/2019

cout.setf(ios::showpoint);
cout.precision(2);

while (in_stream >> rNr >> fine)


{
if (regNr == rNr)
{
totalFines += fine;
cout << "R" << fine << endl;
}
else out_stream << rNr << " " <<fine << endl;
}

cout << "Total fine due R" << totalFines << endl;

in_stream.close();
out_stream.close();
return 0;
}

Output:

OutStandingFines.dat.
DEC234 340
GED345 600
GEE600 120
GED345 230
GEE600 470

Question 4 This question was not marked.


If you attempted the question and produced the correct output, you will get 5 marks. If you
attempted the question, but did not show the correct output, you will get 3 marks. If you did not
attempt the question, you will get 0 marks.

Discussion:
In this question, you were required to write a C++ program that reads telephone numbers from a text
file. The telephone numbers were written in capital letters. After reading the telephone numbers, they
are converted into capital letters. Each and every number was having a letter which it was associated

9
COS1512/201/1/2019

with e.g. A, B, and C are associated to digit 2. If there is any digit which was not part of the list, you
needed to place a “*” in its position.

The first step is to create the input file. We created the input file Phonebook.txt by using the
Code::Blocks editor and creating a new source file, enter the data, and save it as a file with an
extension of .txt. You could also have used Notepad. Save your input file in the same directory where
you save your program.

The header file for the fstream library have to be added to the code with the #include <fstream>
directive

Note that if you create the input file in a directory different from the one where you save your program,
you need to specify the path as well, when specifying the filename, e.g.
C:\COS1512\datafiles\numbers.txt.

When using a file it is essential to test whether the file is available. The following code segment tests
whether the first input file is available before attempting to extract from it:
if (!infile)
{
cout << "Cannot open file " << inName << " Aborting!" << endl;
exit(1);
}

In the above code segment the program is terminated immediately when exit(1) is invoked. We
need to add #include <cstdlib> to our program i.e. the header file for the library that contains this
function.

The next step is to close the output file. It has originally been opened as an output file. However, we
now want to read it to see if the data was written correctly, which means it now has to serve as an
input file, and we have to open it as an ifstream:
outfile.close();

Program listing:

//Ass 1 question 4 - sem 1 -phone number manipulation


#include <iostream> // for screen/keyboard i/o
#include <fstream> // for file
#include <cstdlib> // for exit using namespace std;

using namespace std;

// Precondition:
// The input file is a .txt file containing words/strings for
// telephone numbers. The user will be asked to enter the input file
//name
// Postcondition:
// The output file is a .txt file containing the telephone numbers
// derived from the input file strings. The user will be asked to enter
// the input file name

10
COS1512/201/1/2019

void checkFile(ifstream& infile)


{
char ch;
infile.get(ch);
while(!infile.eof())
{
cout << ch;
infile.get(ch);
}
}

int main()
{

ifstream infile;
ofstream outfile;
ifstream indisplay; //to display the input file ifstream
outdisplay;//to display the output file
string inName, outName;

cout << endl << "Enter the input file name. " << endl;
cin >> inName;
cout << endl << "Enter the output file name. " << endl
<< "WARNING: ANY EXISTING FILE WITH THIS NAME WILL"
<<" BE ERASED." << endl;

cin >> outName;


infile.open(inName.c_str());
if (infile.fail())
{
cout << "Cannot open file "
<< inName << " Aborting!" << endl;
exit(1);
}

outfile.open(outName.c_str());
if (outfile.fail())
{
cout << "Cannot open file "
<< outName << " Aborting!" << endl;
exit(1);
}
int i = 0;
char ch, ch2;
char array1[8];

infile.get(ch);

while(!infile.eof())
{
switch(ch)
{
case 'A': case 'B': case 'C': ch2 = '2';
break;
case 'D': case 'E': case 'F': ch2 = '3';

11
COS1512/201/1/2019

break;
case 'G': case 'H': case 'I': ch2 = '4';
break;
case 'J': case 'K': case 'L': ch2 = '5';
break;
case 'M': case 'N': case 'O': ch2 = '6';
break;
case 'P': case 'Q': case 'R': case 'S': ch2 = '7';
break;
case 'T': case 'U': case 'V': ch2 = '8';
break;
case 'W': case 'X': case 'Y': case 'Z': ch2 = '9';
break;
case ' ': break;
case '\n': break;
default: ch2 = '*';
}

//if we read the newline character, we first display the new


//telephone number stored in array1,
//then clear the array to use again for the next number, and
//then read the next character from the file
if ( ch == '\n' )
{
cout << ' ';
for (int g = 0; g < 8; g ++)
cout << array1[g];
cout << endl;
outfile << '\n';
for (int g = 0; g < 8; g ++)
array1[g] = ' ';
i = 0;
infile.get(ch);
}
//if we read the space character, we display the space on the
// screen and then read the next character from the file
else if (ch == ' ')
{
cout << ' ';
infile.get(ch);
}

//In this case we've read a character which is not a newline


// or space character
else
{
cout << ch;
if (i == 3)
{
array1[i] = ' ';
outfile << ' ';
i++;
}

if (i < 8)
{

12
COS1512/201/1/2019

array1[i] = ch2;
outfile << ch2;
}
infile.get(ch);
i++;
}
} //end while !infile.eof
cout << ' ';
//output final phone number after end-of file has been reached
for (int g = 0; g < 8; g ++)
cout << array1[g];
cout << endl;
cout << endl;
infile.close();
outfile.close();

//This part was not required, but it is always a good idea to read
//the file that was created to make sure it is correct.
//We first read the original input file, and display its content
indisplay.open(inName.c_str());
if (indisplay.fail())
{
cout << "Cannot open file "
<< inName << " Aborting!" << endl;
exit(1);
}

cout << endl << "The contents of the input file is : "<< endl
<< endl;
checkFile(indisplay);
indisplay.close();

//Now we read the file that was created as in the output file and
//display the content
outdisplay.open(outName.c_str());
if (outdisplay.fail())
{
cout << "Cannot open file "
<< outName << " Aborting!" << endl;
exit(1);
}
cout << endl << endl<< "The contents of the output file is : "
<< endl << endl;
checkFile(outdisplay);
outdisplay.close();
return 0;
}

13
COS1512/201/1/2019

OUTPUT:

Question 5 32 marks

(a) A pointer is the memory address of a variable. A variable’s address can be thought of as ‘pointing’
to the variable. See section 9.1 in Savitch. (1)

(b) The deferencing operator is the *operator (the asterisk) used in front of a pointer variable. It
dereferences the pointer variable to produce the variable to which the pointer is pointing to. (1)

(c) Assuming both p1 and p2 have been declared as pointers, i.e. as follows:
int *p1, *p2;
In the assignment statement p1 = p2, the value of one pointer (p2) is assigned to another pointer
(p1) so that the two pointers point to the same memory location. Basically you are using the actual
pointers (addresses of memory locations). With the assignment statement *p1 = *p2, you are
using the actual variables to which the pointers are pointing to so that both variables will have the
same value. (1)

14
COS1512/201/1/2019

(d) A dynamic variable is a variable that is created and destroyed during the execution of the program.
It is created using the new operator. (1)

(e) The new operator produces a new, nameless variable, with a specified data type and returns a
pointer that point to this new variable. This means that the only way the program can access the
variable is through the pointer pointing to it. (1)

(f) The delete operator eliminates (releases or erases) a dynamic variable and returns the memory
that the dynamic variable occupied to the freestore. It releases the memory so that it can be used
for the creation of new dynamic variables. (1)

(g) The freestore (also called the heap) is a special area in memory that is reserved to be used for
dynamic variables. (1)

(h) Dynamic variables are created in a reserved space in memory (the freestore or heap). They are
created and destroyed while the program is running. Automatic variables are automatically created
when the function in which they are declared is called and automatically destroyed when the
function ends. The ordinary variables we use in the programs we write for COS1512 are automatic
variables. (2)

(i) A dynamic array is an array whose size is not specified when it is declared in the program. Instead,
its size is determined while the program is running. (1)

(j) They are flexible in terms of size since the size of the array can be specified during the run time of
the program. This avoids the problem of specifying an array that is too small (not having enough
elements) or too big (wasting computer memory space). (1)

(k) An array variable is a pointer variable that points to the first indexed variable in an array. (1)

(l) For this question, each sub-question is indicated by a comment, followed by the answer to the
sub-question in the program listing below. We show the program code interspersed with
snapshots of the CPU memory for each of the sub-questions in this question below. We also show
the output for the program:

#include <iostream>
using namespace std;
int main()
{
//(i)
? ?
int *p1, *p2; p1 p2

15
COS1512/201/1/2019

//(ii)

int a = 0; a 0 b 100
int b = 100;

//(iii)
p1 = &b; //& is used to indicate the address of variable b
//remember a pointer points to the address of a variable

p1 p2 ?

a 0 b 10
0

//(iv)
p2 = new int;

p1 p2

a 0 b 10 ?
0

//(v)
a = *p1/4; //we use *p1 to refer to the variable that p1 is
//pointing to

p1 p2

a 25 b 10
?
0

16
COS1512/201/1/2019

//(vi)
*p2 = b/a; //we use *p2 to refer to the variable that p2 is
//pointing to

p1 p2

a 25 b 10
4
0

//(vii)
int *p3;

p3 ? p1 p2

a 25 b 10
4
0

//(viii)
p3 = &a; //& is used to indicate the address of variable b
//remember a pointer points to the address of a variable

p3 p1 p2

a 25 b 10
4
0

//(ix)
*p3 = *p2;

p3 p1 p2

a 4 b 10
4
0

17
COS1512/201/1/2019

//(x)
a += 6;

p3 p1 p2

10 10
a b 4
0

//(xi)
*p1 = 2 * *p3;

p3 p1 p2

10 20
a b 4

//(xii)
p1 = p2;

p3 p1 p2

10 20
a b 4

//(xiii)
cout << "The value of the variable that p1 is pointing to is "
<< *p1 << endl; // this value is 4 – see output
cout << "The value of the variable that p2 is pointing to is "
<< *p2 << endl;
cout << "The value of the variable that p3 is pointing to is "
<< *p3 << endl;
cout << "The value of variable a is " << a << endl;
cout << "The value of variable b is " << b << endl;

18
COS1512/201/1/2019

//(xiv)
delete p1, p2, p3;

return 0;
}

Output:

(m) For this question, each sub-question is indicated by a comment, followed by the answer to the
sub-question in the program listing below. We also show the output for the program.

Program listing:
#include <iostream>
using namespace std;
int main()
{
//(i)
int count;
cout << "Please enter an integer value: ";
cin >> count;

//(ii)
typedef int* PtrType;

//(iii)
PtrType p1;

//(iv)
p1 = new int [count];

//(v) (2 marks)
for (int i = 0; i < count; i++)
p1[i] = i;

//(vi)
cout << "The values of the " << count << " elements in the "
<<"dynamic array are" << endl;
for (int i =0; i < count; i++)

19
COS1512/201/1/2019

cout << p1[i] << endl;

//(vii)
delete [] p1;

return 0;
}
Output:

©
UNISA
2019

20

Das könnte Ihnen auch gefallen