You are on page 1of 14

COS1512/201/1/2013

Tutorial Letter 201/1/2013


Introduction to Programming I

COS1512
Semester 1

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

Bar code
CONTENTS
INTRODUCITION ...................................................................................................................................... 2

TUTORIAL MATTER................................................................................................................................. 2

DISCUSSION OF ASSIGNMENT 1 ........................................................................................................... 3


Question 1 ................................................................................................................................................. 3
Question 2 ................................................................................................................................................. 4
Question 3 ................................................................................................................................................. 6
Question 4 ................................................................................................................................................. 9
Question 5 ............................................................................................................................................... 13

INTRODUCITION

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 us with any queries. Please make use of the module
address namely, COS1512-13-S1@unisa.ac.za. Also take note of the following telephone numbers
and the days on which the lecturers are available in case you have to call.

Mondays Petra le Roux 012 429 6008 (Muckleneuk)


Tuesdays Chuma Nombewu 012 429 2102 (Muckleneuk)
Wednesday COS1512 – team
Petra le Roux 012 429 6008 (Muckleneuk)
Chuma Nombewu 012 429 2102 (Muckleneuk)
Samuel Mtsweni 011 471 3019 (Florida)
Thursdays Petra le Roux 012 429 6008 (Muckleneuk)
Fridays Samuel Mtsweni 011 471 3019 (Florida)

TUTORIAL MATTER
You should already have received the material listed below. If any of it is missing, please contact the
Department of Despatch. You may also download it from myUnisa – see tutorial letter
COS1512/101/3/2013 and COSALLF/301/4/2013.

 DISK 2013 (with software)

 Drawing variable diagrams tutorial CD

2
COS1512/1/201

 Tutorial letters:

COSALLF/301/4/2013 General information concerning the School and study


at Unisa
COS1512/101/3/2013  Information about COS1512
 Assignments
 Solutions to self-assessment assignment 3
 Study guide for COS1512
COS1512/201/1/2013 This tutorial letter

Discussion of Assignment 1
Question 1

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 (calcFees() ) with
either two or four parameters of type double. The question did not clearly state whether the
respective fees should be input by the user. We defined two const double variables feeFirst
and feeRepeat for this purpose, but you could have asked the user to input the fees as well.

Program listing:

#include <iostream>
using namespace std;

// overloaded function for tuition fees - first time modules only


// Pre: first time enrolled modules + fees
// Post: returned value is tuition fees
// double calcFees (int nrFirstTime, double tuitionFirst);

// overloaded function for tuition fees - first time and repeated


// modules
// Pre: first time + repeat modules + respective fees
//Post: returned value is tuition fees

double calcFees (int nrFirstTime, const double feeFirst, int


nrRepeat, const double feeRepeat);

const double feeFirst = 1050.00;


const double feeRepeat = 900.00;
int main()
{
char answer;
int nrFirstTime = 0, nrRepeat = 0;
double tuitionAmount = 0.00;

cout << "Does the student repeat any modules? : " << endl;
cin >> answer;
if ((answer == 'y') || (answer == 'Y'))
{
cout << "How many modules will be repeated? : ";

3
cin >> nrRepeat;
}
cout << "How many modules are first time modules? : ";
cin >> nrFirstTime;

if (nrRepeat == 0)
tuitionAmount = calcFees (nrFirstTime, feeFirst);
else
tuitionAmount = calcFees(nrFirstTime,feeFirst,nrRepeat,
feeRepeat);

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
cout << endl <<"The total tuition fee for this student is : R"
<< tuitionAmount << endl;
return 0;
}

//overloaded function for first time modules only


double calcFees (int nrFirstTime, const double feeFirst)
{
return (feeFirst * nrFirstTime);
}

//overloaded function for first time modules and modules that are repeated
double calcFees (int nrFirstTime, const double feeFirst, int nrRepeat,
const double feeRepeat)
{
return (feeFirst * nrFirstTime + feeRepeat * nrRepeat);
}

Input and corresponding output version 1:


Does the student repeat any modules? :
n
How many modules are first time modules? : 6

The total tuition fee for this student is : R6300.00


Press any key to continue . . .

Input and corresponding output version 2:


Does the student repeat any modules? :
y
How many modules will be repeated? : 2
How many modules are first time modules? : 4

The total tuition fee for this student is : R6000.00


Press any key to continue . . .

Question 2

In this question you are required to calculate an average of 5 test scores excluding the lowest score,
where test scores can only be higher than 0 and lower than 100. We used assert macro to ensure
that test scores stay within this range. Note the definition of assert() that had to be included:

4
COS1512/1/201

#include <cassert>

We expected you to check the validity of the test scores with the assert macro. This is of course
also possible without the assert macro.
Typically the assert macro is used to identify program errors during development. The argument
given to assert should be chosen so that it holds true only if the program is operating as intended. The
macro evaluates the assert argument and, if the argument expression is false the program execution
is halted. No action is taken if the argument is true.
Program listing:

#include <iostream>
#include <cassert>
using namespace std;

int main()
{
string studentNr;
int arraySize = 5;
int test[arraySize];
int total = 0, avg;

// Prompt the user for input


cout << "Enter 5 test scores higher than 0 or lower than 100
to calculate average." << endl;
for(int t = 0; t < arraySize; t++)
{
Cout << "Enter marks for test number " << t+1 << endl;
cin >> test[t];
assert(test[t] >= 0 && test[t] <= 100 );
total = total + test[t];
}

//Search for the lowest score


int min = test[0];

for (int j=0; j < arraySize; j++)


{
if (test[j] < min)
{
min = test[j];
}
}

//Calculate Average- i.e. average of the 4 highest score


total = total - min;
avg = total / 4;

//Diplay output - lower score and avarage


Cout << "\nYour lowest score is : "<<min;
Cout << "\nYour average is : "<<avg<<endl;

return 0;
}

5
Input and corresponding output:

Enter test scores higher than 0 or lower than 100 to calculate average.
Enter marks for test number 1
25
Enter marks for test number 2
65
Enter marks for test number 3
32
Enter marks for test number 4
65
Enter arks for test number 5
23

Your lowest score is : 23


Your average is : 46

Question 3

The first step is to create the input file. We created the input file input.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
where you save your program.

The purpose of the program is to ask the user for the name of the input file and then read the file,
manipulate data and then display output on the console. 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 bank.dat and associating the file names with the
ifstream variables, as shown in the statements below:

ifstream infile;
string inName = "bank.dat";

cout << "Please enter the input file name : "<< endl;
cin >> inName;
infile.open(inName.c_str());

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

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:\cos112\datafiles\input.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 (!infile){
cout << "Cannot open file " << inName << " Aborting!" << endl;
exit(1);
}

6
COS1512/1/201

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:

#include <iostream> // for screen/keyboard i/o


#include <fstream> // for file
#include <string> //for string manipulation
#include <cstdlib> // for exit
#include <iomanip> //defines the manipulator functions

using namespace std;

//Declare contestant variables


const double MIN_BALANCE = 1000.00;
const double SERVICE_CHARGE = 25.00;

int main()
{
int accNumber;
double initialBalance;
double accBalance;

double amtDeposited = 0.0;


int noOfDeposits = 0;

double amtWithdrawn = 0.0;


int noOfWithdrawals = 0;
double interestPaid;

char transactionCode;
double transactionAmt;

double bank_cost = 0;
double tot_bank_cost = 0;

ifstream inFile;
string inName;
cout << "Please enter the input file name : "<< endl;
cin >> inName;
inFile.open(inName.c_str());

if (!inFile)
{
cout << "Cannot open file " << inName << " Aborting!" << endl;
exit(1);
}

7
inFile>>accNumber>>initialBalance;
accBalance = initialBalance;

//Output Results heading


cout<< fixed;
cout<< setprecision(2);
cout<<"Account Number: "<<accNumber<<endl<<endl;
cout<<"Opening Balance Balance : R "<<initialBalance<<endl<<endl;

cout<<left<<setw(15)<<"Transaction";
cout<<right<<setw(15)<<"Amount";
cout<<right<<setw(15)<<"Balance";
cout<<right<<setw(15)<<"Bank costs"<<endl;

while(inFile>>transactionCode>>transactionAmt)
{
switch(transactionCode)
{
case 'D':
case 'd': accBalance = accBalance + transactionAmt;
noOfDeposits++;
cout<<left <<setw(15)<<"Deposit";
cout<<right<<setw(15)<<transactionAmt<<"Ct";
cout<<right<<setw(13)<<accBalance<<endl;
break;
case 'I':
case 'i': accBalance = accBalance + transactionAmt;
cout<<left<<setw(15)<<"Interest";
cout<<right<<setw(15)<<transactionAmt;
cout<<right<<setw(15)<<accBalance<<endl;
break;
case 'W':
case 'w': accBalance = accBalance - transactionAmt;
noOfWithdrawals ++;
if(accBalance < MIN_BALANCE)
{
accBalance = accBalance - SERVICE_CHARGE;
bank_cost = bank_cost + SERVICE_CHARGE;
}
cout<<left<<setw(15)<<"Withdrawal";
cout<<right<<setw(15)<<transactionAmt;
cout<<right<<setw(15)<<accBalance;
cout<<right<<setw(15)<<bank_cost<<endl;

tot_bank_cost = tot_bank_cost + bank_cost;


break;
default:
cout<<"Invalid transaction code"<<endl;
}
}

cout<<"\nBanking costs "<<tot_bank_cost;


cout<<"\nClosing Balance R "<<accBalance<<endl;

return 0;
}

8
COS1512/1/201

Input and corresponding output:

Account Number: 46780976

Opening Balance Balance : R 3750.40

Transaction Amount Balance Bank costs


Withdrawal 250.00 3500.40 0.00
Deposit 1200.00Ct 4700.40
Withdrawal 75.00 4625.40 0.00
Withdrawal 1375.00 3250.40 0.00
Deposit 1200.00Ct 4450.40
Interest 5.50 4455.90
Withdrawal 400.00 4055.90 0.00
Withdrawal 600.00 3455.90 0.00
Deposit 450.50Ct 3906.40
Withdrawal 35.65 3870.75 0.00

Banking costs 0.00


Closing Balance R 3870.75

Question 4

The purpose of the program is to read a file character by character. Your task was to write a C++
program that reads a list of telephone numbers expressed in capital letters from a text file and
converts the telephone numbers in capital letters, to the corresponding telephone numbers in digits,
the program must also write another file in which the telephone numbers appear in digital format, one
number per line.

We did not write a function to perform this task – it is performed by the main function. We did, however
write a function to read and display the input file, as well as the output file that was created from the
input file. It is good programming practice to put the code that does all the reading and writing
together.

When implementing our solution, once again the first step is to create the input file. Since the purpose
of the program is to process files, the #include <fstream> and #include <cstdlib>
directives have to be included in the program in order to use the files and to test that they exist before
they are used. The names of the input and output files are requested from the user.

In this program we process the input file as a text file. A text file is typically processed in the following
way:
char ch;
infile.get(ch);
while (!infile.eof())
{
//process ch
infile.get(ch);
}

Compare this to the typical way to read a file containing values that should be processed as int,
string or float (as in Question 3), e.g. a file containing one int followed by a string on each
line:

9
int value;
string name;
while (infile >> value >> name)
{
//process value and name
}

After having created the output file, we added some code to read the input file and display the
contents, as well as some code to do the same for the output file. Note that after the output file is
created and closed, it now acts as an input file if we want to read and display its contents. We
therefore need an ifstream definition. For this purpose we defined:
ifstream indisplay;
ifstream outdisplay;

The first declaration will represent the original input file. The second declaration will represent the
created output file as an input file.

Program listing:

#include <iostream> // for screen/keyboard I/O


#include <fstream> // for file
#include <cstdlib> // for exit

using namespace std;

// Precondition:
// The input file is a text file.
// The input file has been opened.
//
// Postcondition:
// The output file is a text file.
// The output file has been opened.
// Output file will be similar to input file except for all numbers 0 to 7
// that will be replaced with the character as specified in the question

void checkFile(ifstream& outdisplay, ifstream& indisplay )


{
string inputFile, outputFile;
getline(indisplay,inputFile);
getline(outdisplay, outputFile);
while(!indisplay.eof())
{
cout <<inputFile << "\t" << outputFile << endl;
getline(indisplay,inputFile);
cout << "\t";
getline(outdisplay, outputFile);
}
}

int main()
{
ifstream infile;
ofstream outfile;
ifstream indisplay;
ifstream outdisplay;
string inName, outName, line;

cout << endl << "Enter the input file name. " << endl;

10
COS1512/1/201

cin >> inName;


infile.open(inName.c_str());

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

cout << endl << "Enter the output file name. " << endl
<< "WARNING: ANY EXISTING FILE WITH THIS NAME WILL"
<<" BE ERASED." << endl;
cin >> outName;
outfile.open(outName.c_str());
if (outfile.fail())
{
cout << "Cannot open file " << outName << " Aborting!" << endl;
exit(1);
}
char ch;
int counter = 0;

infile.get(ch);

while(!infile.eof())
{
counter++;
switch(ch)
{
case 'A':
case 'B':
case 'C': cout << 2; outfile<<2;
break;
case 'D':
case 'E':
case 'F': cout << 3; outfile<<3;
break;
case 'G':
case 'H':
case 'I': cout << 4; outfile<<4;
break;
case 'J':
case 'K':
case 'L': cout << 5; outfile<<5;
break;
case 'M':
case 'N':
case 'O': cout << 6; outfile<<6;
break;
case 'P':
case 'Q':
case 'R':
case 'S': cout << 7; outfile<<7;
break;
case 'T':
case 'U':
case 'V': cout << 8; outfile<<8;
break;

11
case 'W':
case 'X':
case 'Y':
case 'Z': cout << 9; outfile<<9;
break;

case ' ': cout<<""; outfile<<"";


break;

case '\n': cout<<endl; outfile<<endl;


break;

default: cout<<"*"; outfile<<"*";


break;
}//end switch

if (counter > 6)
{
do
{
infile.get(ch);
} while ( ch != '\n');
counter = 0;
outfile<<endl;
}
infile.get(ch);
}
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());

// Now we read the file that was created as an input file and
// display the ontent
outdisplay.open(outName.c_str());

if (outdisplay.fail() && indisplay.fail() )


{
cout << "Cannot open file(S) Aborting!" << endl;
exit(1);
}
cout << endl <<"The contents of the output file is : " << endl;
checkFile(outdisplay, indisplay);
outdisplay.close();
indisplay.close();
cout << endl;

return 0;
}

12
COS1512/1/201

Question 5

(a) What is a pointer?

A pointer is the memory address of a variable. Pointers provide a way to indirectly name a
variable by naming the address of the variable in the computer’s memory.

(b) What is a dereferencing operator?


It is the *operator that is in front of a pointer variable that produces the variable it points to.
For example:
double *p, v;

(c) What is the difference between


p1= p2;
and
*p1 = *p2;
The first statement assigns the value of one pointer variable to another pointer variable. In the
second statement, you are not dealing with the pointers p1 and p2 but the variables that the
pointers are pointing to.

(d) What is a dynamic variable?


Dynamic variable are variables that are created with the new operator and are created and
destroyed while the program is running.

(e) What is the purpose of the new operator?


The new operator creates a new dynamic variable of a specific type and returns a pointer that
points to this new variable.

(f) What is the purpose of the delete operator?


The delete operator eliminates a dynamic variable and returns the memory that the dynamic
variable occupied to the freestore.

(g) What is the freestore (also called the heap)?


A Freestore is a special area of a memory that is reserved for dynamic variable.

(h) What is the difference between dynamic variables and automatic variables?
Automated variables are the ordinary variables that are automatically created when the
function in which they are declared is called and automatically destroyed when the function call
ends. Dynamic variables are created and destroyed while the program is running.

(i) What is a dynamic array?


A dynamic array is an array whose size is not specified when you write the program but is
determined while the program is running.

(j) What is the advantage of using dynamic arrays?


Dynamic arrays let you declare an array whose size cannot be pre-determining.

(k) What is the relationship between pointers and arrays?


An array variable is, in reality a pointer variable that points to the first indexed variable of the
array.

(l) Write statements to do the following:

13
i. Define a pointer type int_ptr for pointer variables that contain pointers to int
variables.
typedef int* int_ptr ;
ii. Declare p1 to be a pointer to an int.
int *p1;
iii. Dynamically allocate an integer variable and store its address in p1.
p1 = &v1;
iv. Assign the value 23 to the variable that p1 is pointing to.
*p1 = 23;
v. Declare an int variable a.
int a;
vi. Let p1 point to a.
p1 = &a
vii. Free the memory allocated to the variable that p1 is pointing to.
delete p1;

(m) Write statements to do the following:


i. Define a pointer type int_ptr for pointer variables that contain pointers to int
variables.
typedef int* int_ptr ;

ii. Declare p2 to be a pointer to an int.


int *p2;

iii. Obtain an integer value nrElements from the user indicating the number of elements
to allocate.
cin>> nrElements;

iv. Dynamically allocate an array of nrElements integers and store its address in p2.
p2 = &a[nrElements];

v. Declare an int array a with 500 elements.


int a[500];

vi. Assume p2 has been initialized and copy the elements of p2 one by one to the
corresponding elements in a.
for(int x = 0; x < nrElements; x++)
{
p2[nrElements]= nrElements;
}
a = p2;

vii. Free the memory allocated to the variable that p2 is pointing to.
delete [] p2;

©
Unisa
2013

14

You might also like