0% found this document useful (0 votes)
14 views

COS1511 Assignment 2 Semester 1 2024F1

Uploaded by

Syoks Chronicles
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

COS1511 Assignment 2 Semester 1 2024F1

Uploaded by

Syoks Chronicles
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

COS1511

ASSIGNMENT 2
SEMESTER 1 2024
QUESTIONS WITH COMPLETE ANSWERS

[DATE]
[email protected]
[Company address]
COS1511 Assignment 2 Semester 1 2024
Question 1
Write function headers for the functions described below:

(i) The function check has two parameters. The first parameter should be an
integer number and thesecond parameter a floating point number. The function
returns no value.

(ii) The function mult has two floating point numbers as parameters and
returns the result ofmultiplying them.

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

(iv) The function countChar returns the number of occurrences of a character in a string, both
provided as
parameters.

(i) The function check has two parameters: an integer and a floating point number, and it returns no
value.

def check(integer_param: int, float_param: float) -> None:


pass

(ii) The function mult has two floating point numbers as parameters and returns their product.

def mult(float_param1: float, float_param2: float) -> float:


pass

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

def time(seconds: int, minutes: int, hours: int) -> (int, int, int):
pass

(iv) The function countChar returns the number of occurrences of a character in a string, both
provided as parameters.

def countChar(input_string: str, character: str) -> int:


pass

Question 2

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

(i) int function1()


{

cout << "Inside function function1 " <<


endl; int function2()
{

cout << "Inside function function1 " << endl;


}
}

(ii) int sum(int x, int y)


{

int result;
result = x +
y;
}

(iii) int computeProd(int n)


{

if (n == 0)
return 0;

else

n * computeProd(n – 1);

(iv) 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;
}
3
(vi) float calculateSquare(float number)
{

return number * number;


}

(i) The function function1 has a nested function function2 declared inside it, which is not allowed in C++. Also,
there is a missing closing brace for function2.

#include <iostream>
using namespace std;

int function1()
{
cout << "Inside function function1 " << endl;
// Corrected: Remove the nested function declaration.
cout << "Inside function function1 " << endl;
return 0; // Added a return statement.
}

(ii) The function sum does not return any value, but its return type is int.

int sum(int x, int y)


{
int result = x + y;
return result; // Corrected: Added return statement to return the result.
}

(iii) The function computeProd is missing a return statement in the else block and uses an incorrect character for
subtraction (– instead of -).

int computeProd(int n)
{
if (n == 0)
return 0;
else
return n * computeProd(n - 1); // Corrected: Added return statement and fixed the
subtraction operator.
}

(iv) The function aFunction has a redefinition of the parameter a as a local variable, which is not allowed.

void aFunction(float a)
{
// Corrected: Removed the redefinition of 'a'.
cout << a << endl;
}

(v) The function theProduct should not return any value since its return type is void, but it has a return statement
returning result.

void theProduct()
{
int a, b, c;
int result;
cout << "Enter three integers " << endl;
cin >> a >> b >> c;
result = a * b * c;
cout << "Result is " << result << endl;
// Corrected: Removed the return statement.
}

(vi) There is no error in the calculateSquare function.

float calculateSquare(float number)


{
return number * number; // No changes needed.
}

For exam pack with questions and answers, quality notes, assignments and exam help:
email: [email protected]
WhatsApp: +254792947610
Question 3

Write the functions as described below. You need not submit programs that use these functions.

(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.

(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 calculating the difference, subtract the larger value from the smaller
value. Name the function calcSumAndDiff.

(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.

(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 floating pointnumber according
to the rules:

• Small pizza = R50 + R5.50 per topping


• Medium pizza = R70 + R6.50 per topping
• Large pizza = R90 + R7.50 per topping

(i) Function to return the cube of the integer passed to it:

int cube(int n) {
return n * n * n;
}

(ii) Void function to calculate the sum and difference of two integers, with the difference calculated as the absolute
difference:

void calcSumAndDiff(int n1, int n2, int& sum, int& diff) {


sum = n1 + n2;
diff = (n1 > n2) ? (n1 - n2) : (n2 - n1);
}

(iii) Function to print an open rectangle of asterisks with given width and height:

#include <iostream>
using namespace std;
void rectangle(int w, int h) {
if (w < 2 || h < 2) {
cout << "Width and height should be at least 2 to form an open rectangle." << endl;
return;
}

// Print top edge


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

// Print middle part


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

// Print bottom edge


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

(iv) Function to compute the price of a pizza based on its size and number of toppings:

float computePrice(char size, int numToppings) {


float cost;

switch (size) {
case 'S':
case 's':
cost = 50 + 5.50 * numToppings;
break;
case 'M':
case 'm':
cost = 70 + 6.50 * numToppings;
break;
case 'L':
case 'l':
cost = 90 + 7.50 * numToppings;
break;
default:
cout << "Invalid pizza size" << endl;
return -1; // Return an invalid value to indicate error
}

return cost;
}

These functions follow the requirements specified and can be integrated into larger programs as needed.

For exam pack with questions and answers, quality notes, assignments and exam help:
email: [email protected]
WhatsApp: +254792947610

Question 4
The post office needs a program that reads in postal address data and then displays the data in a neat format.
• Declare four string variables name, addr1, addr2 and postalCode.
• First, the main function of the program must input the data by means of a function called inputData.
• 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
Submit the program and the output.

Below is a C++ program that reads in postal address data, stores it in string variables, and then displays it in a neat
format. The program includes the required functions inputData and displayData.

C++ Program
#include <iostream>
#include <string>
using namespace std;

// Function to input data


void inputData(string &name, string &addr1, string &addr2, string &postalCode) {
cout << "Enter name: ";
getline(cin, name);
cout << "Enter address line 1: ";
getline(cin, addr1);
cout << "Enter address line 2: ";
getline(cin, addr2);
cout << "Enter postal code: ";
getline(cin, postalCode);
}

// Function to display data


void displayData(const string &name, const string &addr1, const string &addr2, const string
&postalCode) {
cout << name << endl;
cout << addr1 << " " << addr2 << " " << postalCode << endl;
}

// Main function
int main() {
string name, addr1, addr2, postalCode;

// Input data
inputData(name, addr1, addr2, postalCode);

// Display data
displayData(name, addr1, addr2, postalCode);

return 0;
}

Sample Output
Enter name: Mr R.S. Bopape
Enter address line 1: P.O. Box 50741
Enter address line 2: Sandton
Enter postal code: 2146
Mr R.S. Bopape
P.O. Box 50741 Sandton 2146

This program defines the necessary string variables, reads input from the user through the inputData function, and
displays the formatted address using the displayData function.

To use this program:


1. Compile the program using a C++ compiler.
2. Run the executable and input the required data when prompted.
3. The program will display the formatted address as specified.

Question 5

Write a program that calculates the average of a group of test scores, where the lowest score
in the group is dropped. For example: if the user enters the values 65, 43, 78, 67 and 64, the output
will be:
After dropping the lowest test score, the test average
is 68.50

This average is calculated by dropping the lowest score which is 43 and dividing the sum of the
remaining four values 65, 78, 67 and 64, which is 274, by 4.

It should use the following functions:


• An int function getScore with no parameters, to ask the user for a single test score, validate it and return
the score. The function should be called by the main function once for each of the five scores to be entered.
Do not accept test scores lower than 0 or higher than 100.
• An int function findLowest that is passed the five test scores and then finds and returns the lowest
of the five scores passed to it. It is called by function calcAverage, to determine which of the five scores to
drop.
• A float function calcAverage that is passed the five test scores and then calculates and returns
the average of the four highest scores.
• A void function displayOutput that is passed the average score; it then displays the average of the test
scores. Display two digits after the decimal point.

You must submit the four functions you have developed as well as output using the following 5 sets of
input data:

65 24 80 73 51
66 38 84 69 59
72 52 81 23 53
65 28 72 63 65
65 55 75 68 62

Submit the program and the output.

Below is a complete C++ program that meets the described requirements. The program includes the functions
getScore, findLowest, calcAverage, and displayOutput.

C++ Program
#include <iostream>
#include <iomanip>
using namespace std;

// Function to get and validate a single test score


int getScore() {
int score;
do {
cout << "Enter a test score (0-100): ";
cin >> score;
if (score < 0 || score > 100) {
cout << "Invalid score. Please enter a score between 0 and 100." << endl;
}
} while (score < 0 || score > 100);
return score;
}

// Function to find the lowest score


int findLowest(int scores[], int size) {
int lowest = scores[0];
for (int i = 1; i < size; i++) {
if (scores[i] < lowest) {
lowest = scores[i];
}
}
return lowest;
}

// Function to calculate the average of the highest four scores


float calcAverage(int scores[], int size) {
int lowest = findLowest(scores, size);
int sum = 0;
for (int i = 0; i < size; i++) {
sum += scores[i];
}
sum -= lowest; // Drop the lowest score
return static_cast<float>(sum) / (size - 1); // Divide by the number of remaining scores
}

// Function to display the average score


void displayOutput(float average) {
cout << fixed << setprecision(2);
cout << "After dropping the lowest test score, the test average is " << average << endl;
}

int main() {
const int SIZE = 5;
int scores[SIZE];

// Get the scores from the user


for (int i = 0; i < SIZE; i++) {
scores[i] = getScore();
}

// Calculate the average of the highest four scores


float average = calcAverage(scores, SIZE);

// Display the average score


displayOutput(average);

return 0;
}

Sample Output

For the input set 65 24 80 73 51:

Enter a test score (0-100): 65


Enter a test score (0-100): 24
Enter a test score (0-100): 80
Enter a test score (0-100): 73
Enter a test score (0-100): 51
After dropping the lowest test score, the test average is 67.25

For the input set 66 38 84 69 59:

Enter a test score (0-100): 66


Enter a test score (0-100): 38
Enter a test score (0-100): 84
Enter a test score (0-100): 69
Enter a test score (0-100): 59
After dropping the lowest test score, the test average is 69.50

For the input set 72 52 81 23 53:

Enter a test score (0-100): 72


Enter a test score (0-100): 52
Enter a test score (0-100): 81
Enter a test score (0-100): 23
Enter a test score (0-100): 53
After dropping the lowest test score, the test average is 64.50

For the input set 65 28 72 63 65:

Enter a test score (0-100): 65


Enter a test score (0-100): 28
Enter a test score (0-100): 72
Enter a test score (0-100): 63
Enter a test score (0-100): 65
After dropping the lowest test score, the test average is 66.25

For the input set 65 55 75 68 62:

Enter a test score (0-100): 65


Enter a test score (0-100): 55
Enter a test score (0-100): 75
Enter a test score (0-100): 68
Enter a test score (0-100): 62
After dropping the lowest test score, the test average is 67.50

This program correctly calculates and displays the average of the four highest scores after dropping the lowest score.
The functions are modular and clearly separated according to the requirements.

For exam pack with questions and answers, quality notes, assignments and exam help:
email: [email protected]
WhatsApp: +254792947610

Question 6

Write a program that will compute the volume of a room. User inputs are the height, width and
length of a room. For example, if the user inputs the height as 3, the width as 4 and the length as 5
the volume will be 3 * 4 * 5 = 60. You have to declare three functions: one for input; one to do the
calculation; and one for output.

• The input function getData has to input the height, width and length into the variables theHeight,
theWidth and theLength.
• The calculation function, calculateVolume will receive three parameters that represent the height, width
and length, do the calculation and return the volume of the room.
• The output function displayOutput has to display the height, width and length entered by the user as well
as the volume.
• The program also has to indicate the size of the room as small, medium or large. If the volume is less
than 100, the size is small, between 100 and 500 the size is medium and greater than 500 the size is large.
For example:

The volume of a room with height 3, width 4 and length


5 is 60. Size: Small
The volume of a room with height 10, width 14 and
length 12 is 1680.
Size: Large
The volume of a room with height 7, width 7 and length
7 is 343. Size: Medium

• The main function should include a for loop that allows the user to repeat the calculation of the volume
for new input values five times.
5
You must submit the three functions and the main function you have developed, as
well as outputproduced by the following input data:

345
10 14 12
877
12 14 8
15 8 12

Below is a complete C++ program that calculates the volume of a room, determines the size of
the room based on the volume, and allows the user to repeat the calculation five times. The
program includes the required functions: getData, calculateVolume, and displayOutput.

C++ Program
#include <iostream>
using namespace std;

// Function to input the height, width, and length


void getData(int &height, int &width, int &length) {
cout << "Enter the height of the room: ";
cin >> height;
cout << "Enter the width of the room: ";
cin >> width;
cout << "Enter the length of the room: ";
cin >> length;
}

// Function to calculate the volume of the room


int calculateVolume(int height, int width, int length) {
return height * width * length;
}

// Function to display the height, width, length, volume, and size of the
room
void displayOutput(int height, int width, int length, int volume) {
cout << "The volume of a room with height " << height
<< ", width " << width
<< ", and length " << length
<< " is " << volume << ". ";

// Determine and display the size of the room


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

int main() {
int height, width, length, volume;

// Loop to allow the user to repeat the calculation five times


for (int i = 0; i < 5; ++i) {
getData(height, width, length);
volume = calculateVolume(height, width, length);
displayOutput(height, width, length, volume);
}

return 0;
}

Sample Output

For the input sets provided:

1. Input: 3 4 5

Enter the height of the room: 3


Enter the width of the room: 4
Enter the length of the room: 5
The volume of a room with height 3, width 4, and length 5 is 60. Size:
Small

2. Input: 10 14 12

Enter the height of the room: 10


Enter the width of the room: 14
Enter the length of the room: 12
The volume of a room with height 10, width 14, and length 12 is 1680.
Size: Large

3. Input: 8 7 7

Enter the height of the room: 8


Enter the width of the room: 7
Enter the length of the room: 7
The volume of a room with height 8, width 7, and length 7 is 392. Size:
Medium

4. Input: 12 14 8

Enter the height of the room: 12


Enter the width of the room: 14
Enter the length of the room: 8
The volume of a room with height 12, width 14, and length 8 is 1344.
Size: Large

5. Input: 15 8 12

Enter the height of the room: 15


Enter the width of the room: 8
Enter the length of the room: 12
The volume of a room with height 15, width 8, and length 12 is 1440.
Size: Large

This program correctly calculates the volume of the room, determines its size, and allows the
user to perform the calculation for new input values five times as specified.

For exam pack with questions and answers, quality notes, assignments and exam
help:
email: [email protected]
WhatsApp: +254792947610

Question 7
Draw a series of variable diagrams for the program below. Use the conventions of the Study
Guide.

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 }

Let's draw variable diagrams for the given C++ program, following each important step. I'll
break it down into the main sections of the code execution.

Initial Setup
4 const int C = 200;
5 int func1(int n, int n1) { /*...*/ }
11 void func2(int n, int & n1) { /*...*/ }
16 void func3(int & n, int & n1) { /*...*/ }
23 int main() {
25 int n, m, j;

Initial values:

• C = 200 (constant)
• n = undefined
• m = undefined
• j = undefined

Main Function - Initial Assignments


26 n = 5;
27 m = 10;

Values after assignments:

• n =5
• m = 10
• j = undefined

Calling func1
28 j = func1(n, m);

Values passed to func1:

• n=5
• n1 = 10

Inside func1

7 n += 3; // n = 5 + 3 = 8
8 n1 -= n; // n1 = 10 - 8 = 2
9 return 2 + n + n1 * C; // return 2 + 8 + 2 * 200 = 2 + 8 + 400 = 410

Return value: 410

Values after return from func1:

• n =5
• m = 10
• j = 410

Main Function - Second Set of Assignments


29 n = 15;
30 m = 20;

Values after assignments:

• n = 15
• m = 20
• j = 410

Calling func2
31 func2(n, m);

Values passed to func2:

• n = 15
• n1 (reference to m) = 20

Inside func2

13 n = C * n1; // n = 200 * 20 = 4000


14 n1 = n - n1; // n1 = 4000 - 20 = 3980

Values after func2:

• n = 15 (since it was passed by value, the change doesn't reflect in main)


• m = 3980
• j = 410

Main Function - Third Set of Assignments


32 n = 25;
33 m = 30;
Values after assignments:

• n = 25
• m = 30
• j = 410

Calling func3
34 func3(n, m);

Values passed to func3:

• n (reference to n) = 25
• n1 (reference to m) = 30

Inside func3

19 k = n1 + 3; // k = 30 + 3 = 33
20 n = k * 30; // n = 33 * 30 = 990
21 n1 = n + 2 * k; // n1 = 990 + 2 * 33 = 990 + 66 = 1056

Values after func3:

• n = 990
• m = 1056
• j = 410

Final Values
36 return 0;

Final values:

• n = 990
• m = 1056
• j = 410

Summary

1. Initial values: n = 5, m = 10, j = undefined


2. After func1: n = 5, m = 10, j = 410
3. After reassignments: n = 15, m = 20, j = 410
4. After func2: n = 15, m = 3980, j = 410
5. After reassignments: n = 25, m = 30, j = 410
6. After func3: n = 990, m = 1056, j = 410
This step-by-step variable diagram shows the changes in values at each step of the program's
execution.

For exam pack with questions and answers, quality notes, assignments and exam
help:
email: [email protected]
WhatsApp: +254792947610

You might also like