You are on page 1of 18

COS1511 Assignment 4 2022

written by

tutora

www.stuvia.com

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511
Assignment 4 2022
Unique #: 830369

This document includes:


 Helpful guidelines
 Explanations and/ or calculations
 Study-guide and /or text book references were necessary
 Solutions

Terms of use:

 To be used ONLY for comparison purposes.


 Do not duplicate or distribute without written permission from the author.

Connect with the tutor on


+27 65 505 3119

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

2.2 Notes

If you followed the guidelines given in the questions, got the same output for the given input data,
and used good programming techniques, your programs need not be identical to ours.

In the Study Guide we introduced certain conventions, amongst others


 that names of variables and the names of functions should start with lowercase characters and
further words in the names with uppercase characters,
 that the names of void functions should be verbs (or contain a verb) and
 that the names of value-returning functions should be nouns or adjectives.
Also
 use constants where needed
 avoid the use of global variables
 the correct indenting is extremely important
 remember to include comments

3. Question 1
Take note: Each answer is discussed in detail but the answer to each question in the statement given
in red. That is all that must be given when asked to write function headers.

Write function headers for the functions described below:

(i) The function check()has two parameters. The first parameter should be an integer number
and the second parameter a float number. The function returns no value.

When is it required of you to write a function you have to identify the three basic elements of
a function:
1. The return type of the function
2. The name of the function
3. The parameters of the function

For the function in (i) the elements are:


1. It is stated that the function returns no type – thus the function is a void function.
2. The name of the function is check().
3. There are two parameters ; one integer and one float parameter.

Thus the function definition or header:


void check(int num1, float num2);

1 2 3
Although it is no asked, the implementation of the function would be something like:
void check(int num1, float num2)
{
cout << "Function check! " << endl;
// more statements
}
4

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

And when it is called in the main program:


int main ()
{
check(5,6);
return 0;
}

(ii) The function mult() has two double precision numbers as parameters and returns the
result of multiplying them.

1. The function returns the result of multiplying two double precision numbers. When
multiplying two double precision numbers the result will also be double precision, thus
the function will return a float value.
2. The name of the function is given - mult().
3. There are two double precision parameters; thus float parameters.

Thus the function definition or header:

float mult(float num1, float num2);

For completeness, the function and the calling program:


float mult(float num1, float num2)
{
return num1 * num2;
}

int main ()
{
float x;
x = mult(5.6, 4.9);
return 0;
}

(iii) The function time() inputs seconds, minutes and hours and returns them as parameters to
its calling function.

1. It is stated that the function returns no type – thus the function is a void function.
2. The name of the function is given - time().
3. There are three parameters, and as it is hours, minutes and seconds, in will be
of type integer. But the parameters must keep their respective values and are thus
reference parameters. A reference parameter is indicate with an ampersand '&' sign in
the formal parameter list.

void time (int &s, int &m, int &h);

For completeness, the function and the calling program that demonstrates the use of the
function time():
time (int &s, int &m, int &h)
{
s = 30;
m = 25;

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

h = 18;
}
int main ()
{
int s = 5;
int m = 5;
int h = 5;
cout << "time = " << s <<":"<< m <<":"<< h << endl;
time(s,m,h);
cout << "time = " << s <<":"<< m <<":"<< h << endl;
return 0;
}

(iv) The function countlets()returns the number of occurrences of a character in a string,


both provided as parameters.

1. It is stated that the function returns the number of occurrences of a character in a string
– thus the function will return a value of type integer.
2. The name of the function is given - countlets().
3. There are two parameters: the function must count the number of occurrences of a
certain character in a string. E.g. if the string is 'Hello world' and the character is 'l', the
function must return the value 3. Thus one parameter must represent the string and the
other the character. Thus two parameters one of type sString and the other of type
char.

int countlets(string theString, char theChar);

For completeness, the function and the calling program that demonstrates the use of the
function countlets():

A few remarks:
1. Remember that a string can be treated as an array. So you can look at each
character in the string.
2. To get the size of the string you can use the member function size() as
discussed on p377 in the study guide. Remember to include #include <string>
3. Remember you compare each character in the string with the character, thus using
==.
4. A character is declared with single quotes ' '.
5. Another way of calling the function is
int number = countlets("Hello world", 'l');
6. As the function returns an integer, it can be used in a cout statement as is:
cout << countlets("Hello world", 'l') << endl;
This will display the value 3.
int countlets(string theString, char theChar)
{
int count = 0;
for (int i = 0; i < theString.size(); i++)
{
if (theString[i] == theChar)
count++;
}
return count;
}

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

int main ()
{
string aString = "Hello world";
char aChar = 'l';
int number = countlets(aString, aChar);
cout << "The number of " << aChar << "'s in the string '"
< aString << "' = "<< number << endl;
return 0;
}

(v) The function addAndMultiply has four formal parameters: two int variables named a
and b representing the two values that must be added and multiplied respectively. These
values are returned to the calling program by two reference parameter named added and
multiply.

1. It is stated that the function returns two values. Thus reference parameters must be
used as any function can only return one value – the function returns no value and is
thus a void function.
2. The name of the function is given - addAndMultiply ().
3. There are four parameters: two integer values and two reference parameters. As
the sum and product of two integer values is also of type integer, the reference
variables will be of type integer.
void addAndMultiply(int a , int b, int & added, int & multiply);

Again, although it is no asked, the implementation of the function would be something like:
void addAndMultiply(int a , int b, int & added, int & multiply)
{
added = a + b;
multiply = a * b;
}
int main ()
{
int add = 0;
int mlt = 0;
addAndMultiply(12, 13, add, mlt);
cout << "The sum of the two values = " << add << endl; cout
<< "The product of the two values = " << mlt << endl;
return 0;
}

4. Question 2

Find the error(s) in each of the following program segments and explain how the error(s) can be
corrected:

(i)
int function1()
{
cout << “Inside function function1 “ << endl;
int function2()
{
cout << “Inside function function1 “ << endl;

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

}
}

The function function1 consist of a cout statement and a nested function named
function2. In C++ it is not allowed to have nested functions.
To correct the error, function2 must be defined as a function and be called from
function1.

#include <iostream>
using namespace std;

int function1()
{
cout << "Inside function function1 " << endl;
int y = function2();
}
int function2()
{
cout << "Inside function function2" << endl;
}
int main ()
{
int call = function1();
return 0;
}

(ii)
int sum(int x, int y)
{
int result;
result = x + y;
}

The function sum is declared to return a value of type integer. There is no return
statement in the function. To correct the error, add the return statement as follows:
int sum(int x, int y)
{
int result;
result = x + y;
return result;
}
int main ()
{
int x = sum(5,6);
cout << "The result = " << x;
return 0;
}

(iii)
int computeSum(int n)
{
if (n == 0)
return 0;
else
n + sum( n – 1 );
}

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

This one was a bit difficult and you do not have to be worried if you could not solve it. It is an
example of recursion and you will come across it in COS1512. The correction is that the
function must be called within the function itself.
(iv)
void aFunction(float a)
{
float a;
cout << a << endl;
}

To see the result of the function call, write a little program calling aFunction. It is clear
that the purpose of the function is to display a float value.

int main ()
{
float x = 123.45;
aFunction(x);
return 0;
}

Thus, the expected value to be displayed by calling aFunction(x) is 123.45.


However, the formal parameter a is re-declared in aFunction and C++ does not allow
the re-declaration of formal parameters. To correct the problem, remove the declaration
statement of a in aFunction.

void aFunction(float a)
{
float a;
cout << a << endl;
}

(v)
void theProduct()
{
int a;
int b;
int c;
int result;

cout << “Enter three integers “ << endl;


cin >> a >> b >> c;
result = a * b * c;
cout << “Result is “ << result << endl;
return result;
}

On close inspection of the function, and keeping the three elements of a function in mind, you
see that the function with the name theProduct returns nothing as it is a void function.
There are also no parameters, which is OK. Three integer values are declared as well as
variable named value. After entering the three integer values, result is assigned the
product of the three, which is then displayed. result is then returned. However, the
function is declared to return no value (void) and thus this statement will cause an error and
must be removed.

void theProduct()
{
9

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

int a;
int b;
int c;
int result;

cout << “Enter three integers “ << endl;


cin >> a >> b >> c;
result = a * b * c;
cout << “Result is “ << result << endl;
return result;
}

(vi)
float calculateSquare(float number)
{
float number;
return number * number;
}
It is clear that the purpose of the function is to return the square of two equal float values.
However, the formal parameter number is re-declared in calculateSquare which is not
allowed in C++. To correct the problem, remove the declaration statement of number.

float calculateSquare(float number)


{
float number;
return number * number;
}

5. Question 3

Write the functions as described below:

(i) Write a function that returns the cube of the integer passed to it. For example cube(2) will
return 8 and cube(3) will return 27.

#include <iostream>
using namespace std;

int cube(int number)


{
return number * number * number;
}

int main ()
{
float x = 3;
cout << "cube = " << cube(x) << endl;
return 0;
}

(ii) Write a void function that receives four int parameters: the first two by value and the last two
by reference. Name the formal parameters n1, n2, sum and diff. The function should
calculate the sum of the two parameters passed by value and then store the result in the first
variable passed by reference. It should calculate the difference between the two parameters
passed by value and then store the result in the second parameter passed by reference. When

10

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

calculating the difference, subtract the larger value from the smaller value. Name the function
calcSumAndDiff.
#include <iostream>
using namespace std;

void calcSumAndDiff(int n1, int n2, int & sum, int & diff)
{
sum = n1 + n2;
if (n1 < n2)
diff = n2 - n1;
else
diff = n1 - n2;
}

int main ()
{
int x = 5;
int y = 8;
int theSum = 0;
int theDiff = 0;
calcSumAndDiff(x, y, theSum, theDiff);
cout << "The sum of x and y = " << theSum << endl;
cout << "The differnece between x and y = " << theDiff << endl;
return 0;
}

(iii) Write a function void rectangle(int w, int h) to print an open rectangle of


asterisks (*). The parameters w and h are the width and the height of the rectangle, expressed
in number of asterisks.

#include <iostream>
using namespace std;

void rectangle(int w, int h)


{
for (int i = 0; i < h; i++)
{
for (int j= 0; j < w; j++)
cout << "*";
cout << endl;
}
}

int main ()
{
int x = 5;
int y = 8;
rectangle(x, y);
return 0;
}

(iv) Write a function, computePrice() that receives two parameters: the first one is a
character variable indicating the size of the pizza (S, M or L) and the second an integer variable
indicating the number of toppings on the pizza. It then computes the cost of the pizza and
returns the cost as a double according to the rules:
Small pizza = R50 + R5 per topping
Medium pizza = R70 + R5 per topping
11

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

Large pizza = R90 + R5 per topping

#include <iostream>
using namespace std;

float computePrice(char pizzaSize, int toppings)


{
float price;
switch (pizzaSize)
{
case 'S' : price = (50 * (.55 * toppings));
break;
case 'M' : price = (70 * (.65 * toppings));
break;
case 'L' : price = (90 * (.75 * toppings));
break;
default:
cout << "The size of the pizza given is incorrect!!!";
}
return price;
}

int main ()
{
cout.setf(ios::fixed);
cout.precision(2);

cout << "The Price of the pizza is R" << computePrice('S', 4) << endl;
cout << "The Price of the pizza is R" << computePrice('M', 3) << endl;
cout << "The Price of the pizza is R" << computePrice('L', 5) << endl;
return 0;
}

6. Question 4

The post office needs a program that reads in postal address data and then displays the data in the
correct format.

 Declare four string variables name, addr1, addr2 and postalCode.


 First, the main function of the program must initialise the variables.
 Second, the main function calls the function displayData to display the name and
address as follows:

Mr R.S. Bopape
P.O. Box 50741
Sandton
2146

Write the void function displayData to display the name and address.
Submit the program and the output.

#include <iostream>
using namespace std;

void inputData(string& name, string& addr1, string& addr2, int& postalCode)


{

12

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

cout << " Please enter the name of the recipient : ";
getline(cin, name, '\n');
cout << " Please enter address line 1 : ";
getline(cin, addr1, '\n');
cout << " Please enter address line 2 : ";
getline(cin, addr2, '\n');
cout << " Please enter postal code : ";
cin >> postalCode;
cout << endl;
}

void displayData(string& name, string& addr1, string& addr2, int& postalCode)


{
cout << name << endl;
cout << addr1 << endl;
cout << addr2 << endl;
cout << postalCode << endl;
}

int main ()
{
string theName;
string theAddr1;
string theAddr2;
int thePCode;
inputData(theName, theAddr1, theAddr2, thePCode);
displayData(theName, theAddr1, theAddr2, thePCode);
return 0;
}

When executing the program:


Please enter the name of the recipient: Mr Nel
Please enter address line 1 : PO Box 38763
Please enter address line 2 : Cape Town
Please enter postal code : 1234

Mr Nel
PO Box 38763
Cape Town
1234

Process returned 0 (0x0) execution time : 26.384 s


Press any key to continue.

7. Question 5

#include <iostream>
using namespace std;

int findLowest(int s1, int s2, int s3, int s4, int s5);
int getScore()
{
int score;
cout << "Enter a test score between 0 and 100: ";
cin >> score;
while (score < 0 || score > 100)
{
cout << "Score must be in the range 0 - 100. "

13

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

< "Please re-enter score: ";


cin >> score;
}
return score;

} // end of function getScore

double calcAverage(int s1, int s2, int s3, int s4, int s5)
{
int sum; // Sum of the 4 highest scores
int lowScore; // Low score that will be dropped
double average;

/ Call function findLowest, passing it the 5 scores. When the


/ lowest score is returned, store it in the variable lowScore.
lowScore = findLowest(s1, s2, s3, s4, s5);

sum = s1 + s2 + s3 + s4 + s5 - lowScore;
average = sum / 4.0; // Prevent an integer divide

return average;

}// end of function calcAverage

int findLowest(int s1, int s2, int s3, int s4, int s5)
{
int lowest = s1;

if (s2 < lowest)


lowest = s2;
if (s3 < lowest)
lowest = s3;
if (s4 < lowest)
lowest = s4;
if (s5 < lowest)
lowest = s5;
return lowest;

}// end of function findLowest

void displayOutput(double Average)


{
cout << "\nAfter dropping the lowest test score, the test average is
" << Average << endl;
}

int main()
{
int s1, s2, s3, s4, s5;
s1 = getScore();
s2 = getScore();
s3 = getScore();
s4 = getScore();
s5 = getScore();
double average = calcAverage(s1, s2, s3, s4, s5);
displayOutput(average);
return 0;
}

14

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

8. Question 6
//Determines the volume of a room
#include <iostream>
using namespace std;

void getData(int& height, int& width, int& length )


{
cout << "Calculation of the volume of a room.\n";
cout << "Please enter the height of the room: ";
cin >> height;

cout << "Please enter the width of the room: ";


cin >> width;

cout << "Please enter the length of the room: ";


cin >> length;
}

int calculateVolume(int height, int width, int length)


{
int volume;
volume = height * width * length;
return volume;
}

void displayOutput(int height, int width, int length, int volume )


{
cout << "The volume of a room with height " << height
< " width " << width
< " length " << length
< " is "<< volume ;

if (volume < 100)


cout << " Size: Small" << endl;
if ((volume >= 100) && (volume <= 500))
cout << " Size: Medium" << endl;
if (volume > 500)
cout << " Size: Large" << endl;
}

int main( )
{
int theHeight;
int theWidth;
int theLength;
int theVolume;

for (int i = 0; i < 5; i++)


{
getData(theHeight, theWidth, theLength);
theVolume = calculateVolume(theHeight, theWidth, theLength);
displayOutput(theHeight, theWidth, theLength, theVolume);
}

return 0;
}

15

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

9. Question 7

Draw a series of variable diagrams for the program below. Use the conventions of the Study Guide. Do
not submit this question.
1 // variable diagrams revisited
2 #include <iostream>
3 using namespace std;
4 const int C = 200;
5 int func1(int n, int n1)
6 {
7 n += 3;
8 n1 -= n;
9 return 2 + n + n1 * C;
10 }
11 void func2(int n, int & n1)
12 {
13 n = C * n1;
14 n1 = n – n1;
15 }
16 void func3(int & n, int & n1)
17 {
18 int k;
19 k = n1 + 3;
20 n = k * 30;
21 n1 = n + 2 * k;
22 }
23 int main( )
24 {
25 int n, m, j;
26 n = 5;
27 m = 10;
28 j = func1(n, m);
29 n = 15;
30 m = 20;
31 func2(n, m);
32 n = 25;
33 m = 30;
34 func3(n, m);
35
36 return 0;
37 }

In the solution to this question we follow the variable diagram conventions as given in the Study
Guide, but for clarity’s sake we add an extra box when control jumps back from a value-returning
function (to indicate the value that is being returned).
C
Line 4 200

C n m j
Line 25 200 ? ? ?
m j
C n
Line 26 200 5 ? ?

C n m j
Line 27 200 5 10 ?

C [n] [m] [j] n n1


Line 28→5 200 5 10 ? 5 10

16

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

C [n] [m] [j] n n1


Line 7 200 5 10 ? 8 10
C [m] n n1
[n] [j]
Line 8 200 5 10 ? 8 2
C m
n j return value
Line 9→28 200 5 10 410 410
m j
C n
Line 29 200 15 10 410

C m j
n
Line 30 200 15 20 410

C [m]|n1 [j] n
[n]
Line 31→11 200 20 410 15
15
C
[m]|n1 [j] n
[n]
Line 13 200 20 410 2000
15
C
[m]|n1 [j] n
[n]
Line 14 200 3980 410 4000
15
C
m j
n
Line 15→31 200 3980 410
15
C m j
n
Line 32 200 25 3980 410

C m j
n
Line 33 200 30 410
25
C [m]|n1 [j]
[n]|n
Line 34→16 200 30 410
25

C [m]|n1 [j] k
[n]|n
Line 18 200 30 410 ?
25
C
[m]|n1 [j] k
[n]|n
Line 19 200 30 410 33
25
C
[m]|n1 [j] k
[n]|n
Line 20 200 30 410 33
990
C
[m]|n1 [j] k
[n]|n
Line 21 200 1056 410 33
990
C m j
n
Line 22→34 200 1056 410
990

The aim of this question was to emphasize the difference between parameters that are passed by
value and parameters that are passed by reference.

You should first take note of the constant C. It is declared globally, hence may be used anywhere in
the program. Its value does not change.
17

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

COS1511/202

Function func1 is called in line 28 with the values n = 5 and m = 10 for the actual parameters.
Hence, in func1 the formal parameters have the values n = 5 and n1 = 10. None of these
formal parameters has an associated ampersand & in the header of func1. This means that the
variables n and m are both passed by value, hence the execution of func1 will not influence their
values in the main function. We draw separate boxes for the corresponding formal parameters
(namely n and n1) in our diagram. Further note that func1 is a value-returning function. Before
control jumps back to the main function, an expression is evaluated and this value is then returned
and assigned to j in line 28 when control returns to the main function.

Function func2 is called in the main function (line 31) with the values n = 15 and m = 20 for
the actual parameters. n is passed as a value parameter, so we draw a separate box for the
corresponding formal parameter (also called n) in our diagram. m is passed as a reference
parameter, so the corresponding formal parameter name (namely n1) is a temporary name for m.
Any modification of the value of n1 also modifies the value of m.

Function func3 is called in line 34. Both parameters n and m are passed by reference. This means
that the corresponding formal parameters (namely n and n1, respectively) are temporary names for
them. If n or n1 is changed in func3, the value of n or m is also changed. Further note that k is
a local variable of func3.

Please make sure that you understand every entry of the above diagrams. If you experience any
problems, it will be a good idea to work through Lesson 23 of the Study Guide all over again and also
to work through the Drawing Variable Diagrams CD.

18

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Stuvia.com - The study-notes marketplace

NEED HELP WITH OTHER


ASSESSMENTS?
WhatsApp or Call +27 65 505 3119
Finance Philosophy

Economics Computer science & IT

Accounting Information systems

Business Management Education studies

Strategic Medicine

HRM Pharmacy

Taxation Chemistry

Financial management Lab Reports

Risk management Computer science &

Mathematics and statistics Assignment coaching and guidance

Engineering Online assessments coaching

Basic Numeracy Research proposals, dissertation and


thesis
Quantitative analysis
Proof reading and document design
Financial mathematics
Referencing
Financial modelling
Modelling and programming
Project Management
Business plans
Law
Career guidance
Psychology

UNISA, MONASH, SBS, WITS, UJ, MANCOSA, REGENT, CTI, MGI,


BOSTON, DAMELIN and other Colleges from Certificate to Masters
Levels

Downloaded by: fortunekingyt | fortunekingyt@gmail.com


Distribution of this document is illegal
Powered by TCPDF (www.tcpdf.org)

You might also like