Sei sulla pagina 1di 15

COS1512/201/1/2015

Tutorial letter 201/1/2015


Introduction to Programming II

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

Open Rubric
COS1512/201/1/2015

By the time you receive this tutorial letter you should have already completed assignment 1 and we
hope that you are doing well with your studies. This tutorial letter contains the solutions to Assignment
1. You are welcome to e-mail us with any queries. Please make use of the module address namely,
- -

Also note that each student has been assigned to an e-tutor. Please send your e-tutor an email if you
need help, before contacting the lecturers. Also take note of the following telephone numbers and the
days on which the lecturers are available in case you have to call.

! "
#"

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 75. This is converted to a
percentage. If you for instance obtained 50 marks for Assignment 1, you received 50/75 * 100 = 67%
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.

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. 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/10


Question attempted, but the program does not work at all 4/10
A good attempt, but there are a few problems with your answer 8/10
The program works correctly and produces the correct output 10/10

2
COS1512/201/1/2015

The marks you received for question 2 was determined on the following basis:

This question was not marked. If you attempted the question, you will get 5 marks. If not, you will get 0
marks. Please go through the solution that we give for question 2 to make sure that you understand
the assert() function.

The marks you received for questions 3 and 4 was determined on the following basis:

Question not done 0/15


Question attempted, but the program does not work at all 6/15
A good attempt, but there are a few problems with your answer 11/15
The program works correctly and produces the correct output 15/15

The marks you received for question 5 was determined on the following basis:

One mark each for question 5(a) – (k), that is max 11 marks
One mark each for question 5(l)(i)-(vii) that is max 7 marks
One mark each for question 5(m)(i)-(ii), (v) and (vii) that is max 4 marks
Two marks each for question 5(m)(iii)-(iv), (vi), 5(n) that is max 8 marks
Total number of marks for question 5 is max 30 marks.

3
COS1512/201/1/2015

Question 1

In this question, you were required to write a C++ program to calculate the cost of membership
payable by an organization. The organization is provided with discount when ten or more members are
joining. The cost of membership is calculated by multiplying the number of members by the cost per
person. The program also needs to print the details of the transaction. The program has two functions
namely MemberFee () and PrintDetail (). MemberFee () is a function that calculates the total
cost of membership. This function must be overloaded.

Overloading is a feature in C++ that allows the programmer to define more than one function with the
same name, but with either a different number of function parameters, or with parameters of different
types. The compiler will use either the number of parameters, or the type of parameters to choose
which function to call. The first function will calculate the cost when less than ten members join, and
the second function will calculate the cost when more than ten join. More discussions follows below in
the code. PrintDetail () prints the details of the transaction.
The functions on lines 6 and 10 have the
same function name MemberFee (). The
function is overloaded. The only difference is
Code for the program: the number of parameters in these functions.
In line 4 the function has two parameters and
in line 8, three parameters. The compiler will
1. //Ass1 Q1 Sem1 2015 - function overloading use the number of parameters to decide
2. #include <iostream>
which function to call. For instance: In line
3. #include <iomanip>
31, where the function is called with two
4. using namespace std;
parameters, it will use the function that starts
5.
at line 6. In line 37, MemberFee () is called
6. double MemberFee(double cost, int nrMembers)
with three parameters and it will therefore
7. {
use the function that starts from line 10.
8. return (cost*nrMembers);
9. }
10. double MemberFee (double cost, int nrMembers, double discount)
11. {
12. return (cost * nrMembers) - (( cost * nrMembers ) * discount);
13. }
14. void PrintDetails (double costMembership, double total, int nrJoined)
15. {
16. cout << "Total number of employees that joined: " << nrJoined << endl;
17. cout << "Cost per member R" << costMembership << endl;
18. cout << "Total cost R" << total << endl;
19. }
20. int main()
21. {
22. int NoOfMembers; Note that the calculation here
23. double Discount; will differ if you accepted your
24. double MemberCost, TotalCost; percentage from the user as, for
25. cout << "Enter the number of employees” << example, 10 instead of 0.10.
that want to join our organization: "; Either way is acceptable as the
26. cin >> NoOfMembers; question did not specify the
27. cout << "Please enter the cost of membership R"; format.
28. cin >> MemberCost;
29. if (NoOfMembers < 10)
30. {
31. TotalCost = MemberFee (MemberCost, NoOfMembers);
32. }
33. else
34. {

4
COS1512/201/1/2015

35. cout << "Please enter the discount percentage: ";


36. cin >> Discount;
37. TotalCost = MemberFee (MemberCost, NoOfMembers, Discount);
38. }
39. cout.setf(ios::fixed); cout.setf(ios::fixed) is a
40. cout.setf(ios::showpoint); format option that displays
41. cout.precision(2); floating point numbers in normal
42. PrintDetails (MemberCost, TotalCost, NoOfMembers); notation. cout.precision(2)
43. can be used to indicate the
44. number of digits to be displayed
45. return 0; after the decimal point.
} cout.setf(ios::showpoint
We give an example of a cost with, and without a discount. ) displays decimal point and
trailing zeros for all floating point
numbers, even if the decimal
Output places are not needed.

5
COS1512/201/1/2015

Question 2

You were required to write C++ program that will check if a person qualifies to vote. The person who is
allowed to vote should be at least 18 years of age. The program must check or validate that the year
of birth is not the same as the current year and also not greater than the current year. You were
required to use assert () function.

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>

In the example below:

#include <iostream>
#include <cassert> Header file included to use assert()
using namespace std;

int main()
{
int intYrBirth;
int intCurrentYear = 2015;
int intCurrentAge;
cout << "Please enter year of birth" << endl;
cin >> intYrBirth;
assert((intYrBirth!= intCurrentYear) && (intYrBirth < intCurrentYear));
{
intCurrentAge = intCurrentYear - intYrBirth; assert function is used in this
if (intCurrentAge >= 18) section. The assert function
{
will check if the input meets the
cout << "You are allowed to vote" << endl;
} criteria. The input in this case is
else intYrBirth. If it meets the
{ criteria, the program will
cout << "You are not allowed to vote" << endl; continue. If intYrBirth does
} not meet the criteria, the
} assert function will throw an
system("PAUSE");
return 0; exception error. The criteria are
} that the intYrBirth should
not equal the current year and it
must not be greater than the
current year.
We defined an int variable for the current year and initialised it with the value 2015. For those of you
who are interested, below is a program that uses the localtime() function from the C++ header file
<ctime>, which uses a variable of type time_t. It is not expected of you to know or study this. It is
given for those students who are interested in a more general approach.

//Ass1 question 2
#include <iostream>
#include <ctime>
#include <cassert>

6
COS1512/201/1/2015

using namespace std;

int main()
{
int hour, minute, currentYear, birthYear;
char ans;

// current date/time based on current system


time_t now = time(0);

tm *ltm = localtime(&now);

currentYear = 1900 + ltm->tm_year;


cout << currentYear << endl;

cout << "Please enter your birth year (e.g. 2001): ";

cin >> birthYear;


assert(birthYear != currentYear);
assert(currentYear - birthYear >= 18);
cout << endl << "Congratulations! You are allowed to vote! "<< endl;

return 0;
}
Output:

7
COS1512/201/1/2015

Question 3

In this question, you had to write a C++ program that had to read values from a file called Number.dat,
save them in an array, and then sort the values. The first step is to create the input file. We created
the input file Number.dat 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 .dat. You could also have used Notepad. Save
your input file in the same directory as your program.

After creating a file, you had to write the program that read the numbers from the file and store them
into an array. The array then needs to be sorted in ascending order. After sorting the array, you the
sorted list had to be written to the output file SortedNumber.dat.

#include <cstdlib> One gets input from a file into your program,
#include <iostream> or send output to a file from your program by
#include <fstream> using streams, or special objects as they are
#include <conio.h> called in C++. The type for input-variable
using namespace std; streams is named ifstream, and for output-
variable streams, ofstream.
int main()
One connects the object to the file by
{
opening the file, as is done in the code. We
double dblNumbers[20], r;
int intCountNumbers = 0; include the fstream header file as well.
ifstream in_stream; Please see section 6.1 of Savitch for more
in_stream.open("Numbers.dat"); information.

if(in_stream.fail())
{
cout << "Failed to open a file" << endl;
system("PAUSE");
exit(0);
}
else
{
while(!in_stream.eof())
{
in_stream >> dblNumbers[intCountNumbers];
intCountNumbers = intCountNumbers + 1;
}
}
in_stream.close();
int i;
cout <<"Unsorted list of numbers from a file"<< endl << endl;
for (i = 0; i < 20; i++)
{
cout << dblNumbers[i] << endl;
}
// Sorting the array
for (int k = 0; k < 20; k++)
{
for(int p = 0; p < 19; p++)
{

8
COS1512/201/1/2015

if(dblNumbers[p] > dblNumbers[p + 1])


{
r = dblNumbers[p];
dblNumbers[p] = dblNumbers[p + 1];
dblNumbers[p + 1] = r;
}
}
}

cout <<endl << "Sorted list of numbers written to an output file" << endl;
for (i = 0; i < 20; i++)
{
cout <<dblNumbers[i] << endl;
}
One should always check whether a file
ofstream out_stream; has been opened or closed
out_stream.open("SortedNumber.dat"); successfully. The member function
if(out_stream.fail()) fail() does exactly that. It returns a
{ Boolean value of false if the file
cout << "Failed to open a file" << endl; opened/closed successfully, and allows
system("PAUSE"); the program to continue. Please read
exit(0); section 6.1 in Savitch for further
} information
else
{
for (int o = 0; o < 20; o++)
{
out_stream << dblNumbers[o] << endl;
}
}
out_stream.close();
system("PAUSE");
}

Output:

Please turn the page.

9
COS1512/201/1/2015

Question 4

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
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);

10
COS1512/201/1/2015

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;

// 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
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);

11
COS1512/201/1/2015

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'; 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)
{

12
COS1512/201/1/2015

array1[i++] = ' ';


outfile << ' ';
}

if (i < 8)
{
array1[i] = ch2;
outfile << ch2;
}
i++;
infile.get(ch);
}

} //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;
}

OUTPUT:

13
COS1512/201/1/2015

Question 5

(a) A pointer holds the memory address or address in memory of a variable. A variable’s address
can be thought of as ‘pointing’ to the variable.
(b) The dereferencing operator is also called indirection operator is represented by an asterisk. It
dereferences the pointer. It produces the value of the variable to which the pointer is pointing.
(c) In p1 = p2, the value of one pointer is assigned to another pointer. Basically you are using
the actual pointers (addresses of memories). In *p1 = *p2, the value of the variable that p2
is pointing to, is assigned to the variable that p1 is pointing to..
(d) A dynamic variable is a variable that is created (and therefore allocated memory) during the
execution of the program. It is created using “new” operator.
(e) The new operator produces a new, nameless variable, with a specified data type and returns a
pointer that points to this new variable. This variable’s value is then manipulated via the
pointer(s) pointing to it.
(f) The delete operator eliminates a dynamic variable and returns the memory that the dynamic
variable occupied to the freestore. It makes the memory available to be used for example for
creation of dynamic variables.
(g) Freestore also called heap is a special area in memory that is reserved to be used for dynamic
variables.
(h) Dynamic variables have a reserved space in memory, and they are created and destroyed
while the program is running, while automatic variables are automatically created when the
function in which they are declared is called and automatically destroyed when the function
ends.
(i) A dynamic array is an array which size is not specified during its declaration but its size is
determined during runtime.

14
COS1512/201/1/2015

(j) They are flexible in terms size since the size of the array can change during the runtime of the
program.
(k) An array is a pointer variable that points to the first indexed variable in an array.
(l)

i. int *int_ptr;
ii. int *p1;
iii. p1 = new int;
iv. *p1 = 23;
v. int a;
vi. p1 = &a;
vii. delete p1;

(m)
i. int *int_ptr;
ii. int *p2;

iii. int nrElements;


cout << “Enter number of elements “<< endl;
cin >> nrElements;
iv. p2 = new int [nrElements];

v. int a[500];
vi. for (int i = 0; i < 500; i ++)
*p2[i] = a[i];
vii. delete [] p2;

(n) 40
40

UNISA
2015

15

Potrebbero piacerti anche