Professional Documents
Culture Documents
written by
tutora
www.stuvia.com
COS1511
Assignment 4 2022
Unique #: 830369
Terms of use:
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.
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.
(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
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
COS1511/202
(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.
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.
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;
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;
}
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.
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;
}
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;
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 );
}
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;
}
void aFunction(float a)
{
float a;
cout << a << endl;
}
(v)
void theProduct()
{
int a;
int b;
int c;
int 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
COS1511/202
int a;
int b;
int c;
int 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.
5. Question 3
(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 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
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;
}
#include <iostream>
using namespace std;
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
COS1511/202
#include <iostream>
using namespace std;
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.
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;
12
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;
}
int main ()
{
string theName;
string theAddr1;
string theAddr2;
int thePCode;
inputData(theName, theAddr1, theAddr2, thePCode);
displayData(theName, theAddr1, theAddr2, thePCode);
return 0;
}
Mr Nel
PO Box 38763
Cape Town
1234
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
COS1511/202
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;
sum = s1 + s2 + s3 + s4 + s5 - lowScore;
average = sum / 4.0; // Prevent an integer divide
return average;
int findLowest(int s1, int s2, int s3, int s4, int s5)
{
int lowest = s1;
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
COS1511/202
8. Question 6
//Determines the volume of a room
#include <iostream>
using namespace std;
int main( )
{
int theHeight;
int theWidth;
int theLength;
int theVolume;
return 0;
}
15
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 ?
16
COS1511/202
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
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
Strategic Medicine
HRM Pharmacy
Taxation Chemistry