You are on page 1of 26

COS1511/202/1/2011

Introduction to programming 1
Tutorial letter 202/1 for COS1511

Solutions to Assignment 2 of the first semester


Due to regulatory requirements imposed by the Department of National Education the following apply: To be considered for examination admission in COS1511, a student must meet the following requirement: Submit assignment 1 BEFORE 7 March 2011

School of Computing

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 the Internet (myUnisa see Tutorial Letters COS1511/101/3/2011 and COSALLF/301/4/2011.

Study Guide
DISK 2011 (with software) Tutorial letters: COSALLF/301/4/2011 General information concerning the School and study at Unisa COSALLF/302/4/2011 Names and telephone numbers of lecturers COS1511/101/3/2011 Information about COS1511 Assignments COS1511/102/3/2011 Solutions to exercises in the Study Guide COS1511/103/1/2011 Invitation to Discussion Class COS1511/104/3/2011 Examination Tutorial Letter COS1511/201/1/2011 Solutions to assignment 1 COS1511/202/1/2011 This letter

For e-mail, please use the module address namely COS1511-11-S1@.unisa.ac.za It is possible to have discussions with fellow students on the forums on myUnisa and osprey (see tutorial letter COSALLF/301/4/2011). You may phone us at any of the following telephone numbers: Ms HW du Plessis 012-4296860 Ms P le Roux 012-4296008

COS1511/202/1

SEMESTER MARK Assignments 1 and 2 contribute towards your semester mark for this module. Assignment 1 carries a weight of 30% and Assignment 2 a weight of 70%. The semester mark contributes 10% to the final mark for this module. Suppose a student gets 60% for Assignment 1 and 50% for Assignments 2. In order to calculate the semester mark, the mark obtained for the specific assignment is multiplied by the weight. This then forms part of the 10% that the semester mark contributes to the final mark. Therefore: Assignment 1 2 3 TOTAL Marks obtained 60% 50% Weight 30% 70% 0% Contribution to semester mark 60/100 x 30/100 x 10 50/100 x 70/100 x 10 1.80 3.50 5.30

Hence, in this example the semester mark is 5.30. Note that the semester mark will not form part of the final mark if the supplementary examination is written.

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. NOTE: 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.

Use constants where needed. Avoid the use of global variables. We also want to stress again that correct indenting is extremely important. Also, remember to include comments.

QUESTION 1: Question 1a

Short answers

The two bank balances may not be the same. The balances may also not be less than zero. Therefore, the loop should continue while balance1 < 0 or balance2 < 0 or bankAccount1 is equal to bankAccount2. Thus the condition should be:
while( (bankAccount1 == bankAccount2) || (balance1 < 0) || (balance2 < 0))

Below, is a sample program to illustrate :


#include <iostream> using namespace std; int main() { int bankAccount1; int bankAccount2; float balance1; float balance2; cout<<"Enter first bank account number: "; cin>>bankAccount1; cout<<" Enter second bank account number: "; cin>>bankAccount2; cout<<"Enter the balance of first account: "; cin>>balance1; cout<<"Enter the balance of the second account :"; cin>>balance2; while( (bankAccount1 == bankAccount2) || (balance1 < 0) || (balance2 < 0)) { cout<<"Re-enter values" <<endl; if (bankAccount1 == bankAccount2) { cout<<"Enter first bank account number: "; cin>>bankAccount1; cout<<" Enter second bank account number: "; cin>>bankAccount2; } if (balance1 < 0) { cout<<"Enter the balance of first account: "; cin>>balance1; } if (balance2 < 0) { cout<<"Enter the balance of second account: "; cin>>balance2; } } return 0; }

COS1511/202/1

Question 1b Note that it is necessary to declare i before the while loop, and initialize it to 1. int i = 1; while(i <= 10) { cout<<"i is now :" <<i<<endl; i = i + 3; } Question 1c 2 23 49 305 613 3689 The loop is executed for i i = 0: j j i is even: i = 1: j j i = 2: j j i is even: i = 3: j j i = 4: j j i is even: i = 5: j j = 0, i = 1, i = 2, i = 3, i = 4 and i = 5: is printed : 2 gets changed to :j = 2 * 2 + 3 = 7 j gets changed to: j = 3 * 7 + 2 = 23 is printed : 23 gets changed to :j = 2 * 23 + 3 = 49 is printed : 49 gets changed to :j = 2 * 49 + 3 = 101 j gets changed to: j = 3 * 101 + 2 = 305 is printed : 305 gets changed to :j = 2 * 305 + 3 = 613 is printed : 613 gets changed to :j = 2 * 613 + 3 = 1229 j gets changed to j = 3 * 1229 + 2 = 3689 is printed : 3689 gets changed to :j = 2 * 3689 + 3 = 7381

Question 1d Missing fragments shown in bold.


#include <iostream> using namespace std; int main() { float cents = 0.01; float total = 0; total = cents; cout <<"Day cout <<"1 for(int i = 2; i <= 30; i++) { cents = cents * 2;

Amount"<<endl; "<<cents<<endl;

cout<<i<<" total = total + cents; }

"<<cents<<endl;

cout<<"Sibusiso must pay his sister a total of : "<<total<<endl; }

QUESTION 2:

Nested loops

Note the use of constant variables in the program. This program contains two nested loops. The outermost loop is a for loop that runs over the number of salesmen. A while loop is used to validate the staff number that has to be between 999 and 9999(inclusive). The inner loop is also a for loop that runs over the number of grades. For each grade, the grade sale amount is entered and the gross salary is updated by using the commission for the specific grade in the calculation. Then the total sale amount is updated. A switch statement is used to determine the correct commission amount for the specific grade. The nested ifelse structure is used to determine which income tax rate to use for each different salary bracket. Also note the use of the two statements cout.setf(ios::fixed); and cout.precision(2); in the main function. The first statement prevents the computer from displaying floating point numbers in scientific notation. The second statement specifies the number of digits we want to display after the decimal point. Refer to Lesson 6 in the study guide for a detailed explanation of the precision statement. We have used cout.width() to display and align the amount fields on the payslip. Because width() is a member function, it must be invoked with a cout object. One can set the width of a field, as we have done. Weve chosen 10, which will be wide enough for the staff number and the amount fields. cout.width() only changes the width of the very next output field and then immediately reverts to the default. The default width of the output will be just enough space to print the number, character, or string in the output buffer. One can change this by using width(). It aligns the amounts properly. You will not be tested on cout.width() in the exam. A correct program is given below. NB: Note the indentation of the code. Program: // First semester 2011 Assignment Question 2

#include <iostream> using namespace std; int main() { int numSalesmen; int staffNumber; float commission; float tax; float netSalary; float medicalAid; float gradeSales; float totalSales = 0; float grossSalary = 0;

COS1511/202/1

const const const const const const const const const const

float float float float float float float float float float

superIncomeTaxRate = 0.5; highIncomeTaxRate = 0.4; midIncomeTaxRate = 0.3; lowIncomeTaxRate = 0.2; lowestIncomeTaxRate = 0.1; gradeACommission gradeBCommission gradeCCommission gradeDCommission gradeECommission = = = = = 0.2; 0.18; 0.15; 0.1; 0.05;

cout << "Enter the number of salesman for Company ABC : "; cin >> numSalesmen; //for loop iterate over number of salesmen for(int i = 0; i < numSalesmen ; i++) { cout<<"Enter the staff number for salesman " << i + 1 << " : "; cin >> staffNumber; //validate staff number while (staffNumber < 999 || staffNumber > 9999) { cout << "Please re-enter staff number (between 999 - 9999) :"; cin >> staffNumber; } cout<< "Enter the medical aid contribution for staff number " << staffNumber << " : R"; cin >> medicalAid; //for iterate over the grades for (int j = 1 ; j <= 5 ; j++) { switch (j) { case 1 : cout << "Enter total sales for commission = gradeACommission; break; case 2 : cout << "Enter total sales for commission = gradeBCommission; break; case 3 : cout << "Enter total sales for commission = gradeCCommission; break; case 4: cout << "Enter total sales for commission = gradeDCommission; break; case 5: cout << "Enter total sales for commission = gradeECommission; break; }//end switch statement

Grade A: R"; Grade B: R"; Grade C: R"; Grade D: R"; Grade E: R";

cin >> gradeSales; //determine gross salary grossSalary = grossSalary + gradeSales*commission; //determine totalSales totalSales = totalSales + gradeSales; }//end inner for-loop //nested if statement to determine taxes

if (grossSalary >= 20000.00) tax = grossSalary*superIncomeTaxRate; else if (grossSalary >= 15000.00) tax = grossSalary*highIncomeTaxRate; else if (grossSalary >= 10000.000) tax = grossSalary*midIncomeTaxRate; else if (grossSalary >= 5000.00) tax = grossSalary*lowIncomeTaxRate; else tax = grossSalary*lowestIncomeTaxRate; //determine if salesman gets rebate if (medicalAid >= (0.1*grossSalary) && grossSalary < 5000.00) { //rebate tax = tax*0.5; } //determine net salary netSalary = grossSalary - tax - medicalAid; cout.setf(ios::fixed); cout.precision(2); //display payslip cout << ".................PAY SLIP....................." << endl; cout << "Staff Number : # " ; cout.width(10); cout<< staffNumber << endl; cout << "Gross Salary : R " ; cout.width(10); cout<< grossSalary << endl; cout << "Tax Deducted : R " ; cout.width(10); cout<< tax << endl ; cout << "Medical Aid : R " ; cout.width(10); cout<< medicalAid <<endl; cout << "Net Salary : R " ; cout.width(10); cout<< netSalary << endl ; cout << ".............................................." << endl <<endl; //reset grossSalary to 0 for next salesman grossSalary = 0; }//end of outer for-loop //display total sales cout<<" Total Sales for this month : return 0; } Test Data: Enter the number of salesman for Company ABC : 2 Enter the staff number for salesman 1 : 1002 Enter the medical aid contribution for staff number 1002 : R200.00 Enter total sales for Grade A: R20000.00 Enter total sales for Grade B: R1000.00 Enter total sales for Grade C: R1000.00 R" << totalSales << endl;

COS1511/202/1

Enter total sales for Grade D: R2000.00 Enter total sales for Grade E: R2000.00 .................PAY SLIP..................... Staff Number : # 1002 Gross Salary : R 4630.00 Tax Deducted : R 463.00 Medical Aid : R 200.00 Net Salary : R 3967.00 .............................................. Enter the staff number for salesman 2 : 1111 Enter the medical aid contribution for staff number 1111 : R3000 Enter total sales for Grade A: R20000.00 Enter total sales for Grade B: R0 Enter total sales for Grade C: R0 Enter total sales for Grade D: R1000.00 Enter total sales for Grade E: R0 .................PAY SLIP..................... Staff Number : # 1111 Gross Salary : R 4100.00 Tax Deducted : R 205.00 Medical Aid : R 3000.00 Net Salary : R 895.00 .............................................. Total Sales for this month : R47000.00 Press any key to continue . . .

QUESTION 3:

void functions with one or more value parameters

NOTE: The question illustrates void functions, as well as the powerful use of the for loop. You will not be expected to write such a function in the exam. We develop the program in two steps. Marks were allocated for Question 3b. Question 3a: One value parameter

The function drawPattern does not return a value. Therefore its return type is void. There is one value parameter of type int. The function has one parameter of type int, representing the size of the pattern. The function uses a nested for loop. The outer loop runs from 1 to sizeP * sizeP. This will handle the rows of the pattern, in other words with every iteration of the outer loop, one row of the figure is displayed on the screen. The inner for loop also runs from 1 to sizeP * sizeP, completing each column, in other words. The inner loop handles the sizeP groups of s and O characters. We tested whether i and j is odd or even to decide whether the group should consist of s or O characters. The main function asks the user to input the size, and then calls the function drawPattern with the size entered. The coding for the main function should have been easy for you. Program:
//Assignment 2 question 3a #include <iostream> using namespace std;

10

void drawPattern(int sizeP) { for (int i = 0; i < (sizeP * sizeP) ; i++) { cout << endl; for (int j = 0; j < (sizeP * sizeP); j++) { if ( (i / sizeP) % 2 == 0) if ((j / sizeP) % 2 == 0) cout << 's'; else cout << 'O'; else if ((j / sizeP) % 2 == 0) cout << 'O'; else cout << 's'; } } } int main() { int number = 0; cout << "Please enter the size of the pattern(max size of 10) : " << endl; cin >> number; drawPattern(number); } return 0;

Question 3b:

Three value parameters

In the program below function drawPattern has been changed such that the user is able to specify the character that should be used for the group that starts the pattern, as well as the character for every alternate group. We therefore added two parameters to the function header. The main function has also been changed to ask the user to input both these characters and call the function drawPattern with the size of the pattern as well as the two input fields as parameters. Program:
// Assignment 2 Question 3b #include <iostream> using namespace std; void drawPattern(int sizeP, char startP, char nextP) { for (int i = 0; i < (sizeP * sizeP) ; i++) { cout << endl; for (int j = 0; j < (sizeP * sizeP); j++) { if ( (i / sizeP) % 2 == 0) if ((j / sizeP) % 2 == 0) cout << startP; else cout << nextP; else

11

COS1511/202/1

if ((j / sizeP) % 2 == 0) cout << nextP; else cout << startP; } } } int main() { int number = 0; char start, next; cout << "Please enter the size of the pattern(max size of 10) : " << endl; cin >> number; cout << "Please enter the start character : " << endl; cin >> start; cout << "Please enter the next character : " << endl; cin >> next; drawPattern(number, start, next); return 0; }

Output:

Please enter the size of the pattern(max size of 10) : 4 Please enter the start character : Y Please enter the next character : + YYYY++++YYYY++++ YYYY++++YYYY++++ YYYY++++YYYY++++ YYYY++++YYYY++++ ++++YYYY++++YYYY ++++YYYY++++YYYY ++++YYYY++++YYYY ++++YYYY++++YYYY YYYY++++YYYY++++ YYYY++++YYYY++++ YYYY++++YYYY++++ YYYY++++YYYY++++ ++++YYYY++++YYYY ++++YYYY++++YYYY ++++YYYY++++YYYY ++++YYYY++++YYYY

QUESTION 4:

Value returning functions with one and two value parameters

We give the solution in several steps but you had to submit the program and output of Question 4c only. Marks were allocated for Question 4c. Question 4a: Start small

Here you had to write a value returning function with one value parameter. From the calling statement, namely amtGift = calcAllowedPerChild(nrChildren);

12

and the declaration of amtGift as float it should be clear that the function has a return type of float. The body of the function is very simple: it consists of a division instruction to calculate the amount allowed per child. It then checks that the amount allowed per child is not less than the minimum amount or greater than the maximum amount as specified in the question, and changes the amount accordingly, if necessary. Also note the use of the two statements cout.setf(ios::fixed); and cout.precision(2); in the main function. The first statement prevents the computer from displaying floating point numbers in scientific notation. The second statement specifies the number of digits we want to display after the decimal point. Refer to Lesson 6 in the study guide for a detailed explanation of the precision statement. Program:
//Assignment 2 Question 4a

#include <iostream> using namespace std; const float maxPerUnit = 20000.00; //minPerChild includes a standard gift consisting //of a bath towel and a facecloth const float minPerChild = 100.00; const float maxPerChild = 180.00; //depending on the amount, the child may also get //one or more of the following: const float TOOTHBRUSH = 29.95; const float HIGHLIGHTERS = 25.95; const float CRAYONS = 17.95; const float NOTEBOOK = 12.95; const float PEN = 9.99; float calcAllowedPerChild(int nrChildrenP) { float amount; amount = maxPerUnit / nrChildrenP; if (amount > maxPerChild) amount = maxPerChild; if (amount < minPerChild) amount = minPerChild; return amount; } int main() { float amtGift; //Allowed amount per child float amtSpentPerChild = 0.00; //actual amount spent per child float totalSpent = 0.00; //total spent for one orphanage float totalAll = 0.00; //total spent for all 4 orphanages int nrChildren; //number of children per orphanage cout << " Enter the number of children: " << endl; cin >> nrChildren; amtGift = calcAllowedPerChild(nrChildren); cout.setf(ios::fixed); cout.precision(2); cout << endl << " Allowable amount per child : R" << amtGift; cout << endl << endl; } return 0; }

13

COS1511/202/1

Question 4b: Slightly larger Here you had to write two functions function calcActualAmount, that receives two value parameters which are float and int for the allowable amount per child and the number of children respectively, and the function calcTotalSpent that receives two value parameters of type int and float , representing the number of children and the actual amount spent per child. Function calcActualAmount returns the actual amount spent per child, and function calcTotalSpent calculates the total amount spent per orphanage. Note how function calcActualAmount adds items with the highest value first, as specified in the question. Function calcTotalSpent consists of a single multiplication statement to calculate the total spent for the orphanage. Program:
//Assignment 2 Question 4b

#include <iostream> using namespace std; const float maxPerUnit = 20000.00; //minPerChild includes a standard gift consisting //of a bath towel and a facecloth const float minPerChild = 100.00; const float maxPerChild = 180.00; //depending on the amount, the child may also get //one or more of the following: const float TOOTHBRUSH = 29.95; const float HIGHLIGHTERS = 25.95; const float CRAYONS = 17.95; const float NOTEBOOK = 12.95; const float PEN = 9.99; float calcAllowedPerChild(int nrChildrenP) { float amount; amount = maxPerUnit / nrChildrenP; if (amount > maxPerChild) amount = maxPerChild; if (amount < minPerChild) amount = minPerChild; return amount; } float calcActualAmount(float amtGiftP, int nrChildrenP) { float amount = 0.00; amount += minPerChild; if (amtGiftP - amount >= TOOTHBRUSH) amount += TOOTHBRUSH; if (amtGiftP - amount >= HIGHLIGHTERS) amount += HIGHLIGHTERS; if (amtGiftP - amount >= CRAYONS) amount += CRAYONS; if (amtGiftP - amount >= NOTEBOOK) amount += NOTEBOOK; return amount; } float calcTotalSpent(int nrChildrenP, float amtSpentPerChildP){ return (nrChildrenP * amtSpentPerChildP); }

14

int main() { float amtGift; //Allowed amount per child float amtSpentPerChild = 0.00; //actual amount spent per child float totalSpent = 0.00; //total spent for one orphanage float totalAll = 0.00; //total spent for all 4 orphanages int nrChildren; //number of children per orphanage cout << " Enter the number of children: " << endl; cin >> nrChildren; amtGift = calcAllowedPerChild(nrChildren); cout.setf(ios::fixed); cout.precision(2); cout << endl << " Allowable amount per child : R" << amtGift; cout << endl << endl; amtSpentPerChild = calcActualAmount(amtGift, nrChildren); cout << endl << " Actual amount spent per child : R" ; cout << amtSpentPerChild << endl << endl; totalSpent = calcTotalSpent(nrChildren, amtSpentPerChild); cout << endl << " The actual amount spent was : R" ; cout << totalSpent << endl; return 0;

} Question 4c: Add a loop to the main function

Here you had to add a loop in the program, repeating the process for four orphanages. We used a for loop. The complete program and output follow below. Program:
#include <iostream> using namespace std; const float maxPerUnit = 20000.00; //minPerChild includes a standard gift consisting //of a bath towel and a facecloth const float minPerChild = 100.00; const float maxPerChild = 180.00; //depending on the amount, the child may also get //one or more of the following: const float TOOTHBRUSH = 29.95; const float HIGHLIGHTERS = 25.95; const float CRAYONS = 17.95; const float NOTEBOOK = 12.95; const float PEN = 9.99; float calcAllowedPerChild(int nrChildrenP) { float amount; amount = maxPerUnit / nrChildrenP; if (amount > maxPerChild) amount = maxPerChild; if (amount < minPerChild) amount = minPerChild; return amount; } float calcActualAmount(float amtGiftP, int nrChildrenP) {

15 float amount = 0.00; amount += minPerChild; if (amtGiftP - amount >= TOOTHBRUSH) amount += TOOTHBRUSH; if (amtGiftP - amount >= HIGHLIGHTERS) amount += HIGHLIGHTERS; if (amtGiftP - amount >= CRAYONS) amount += CRAYONS; if (amtGiftP - amount >= NOTEBOOK) amount += NOTEBOOK; if (amtGiftP - amount >= PEN) amount += PEN; return amount; } float calcTotalSpent(int nrChildrenP, float amtSpentPerChildP){ return (nrChildrenP * amtSpentPerChildP); } int main() { float amtGift; float amtSpentPerChild = 0.00; float totalSpent = 0.00; int nrChildren; float totalAll = 0;

COS1511/202/1

for (int i = 1; i <=4; i++) { cout << endl << endl << "Institution " << i << " :" << endl << endl; cout << " Enter the number of children: " << endl; cin >> nrChildren; amtGift = calcAllowedPerChild(nrChildren); cout.setf(ios::fixed); cout.precision(2); cout << endl << " Allowable amount per child : R" << amtGift << endl << endl; amtSpentPerChild = calcActualAmount(amtGift, nrChildren); cout << endl << " Actual amount spent per child : R" << amtSpentPerChild << endl << endl; totalSpent = calcTotalSpent(nrChildren, amtSpentPerChild); cout << endl << " The actual amount spent was : R" << totalSpent << endl; totalAll += totalSpent; } cout << endl << " Total for 4 orphanages was : R" << totalAll << endl; return 0; }

Output:
Institution 1 : Enter the number of children: 65 Allowable amount per child : R180.00

Actual amount spent per child : R173.85

16

The actual amount spent was Institution 2 : Enter the number of children: 123 Allowable amount per child

: R11300.25

: R162.60

Actual amount spent per child : R155.90 The actual amount spent was Institution 3 : Enter the number of children: 167 Allowable amount per child : R119.76 : R19175.70

Actual amount spent per child : R117.95 The actual amount spent was Institution 4 : Enter the number of children: 230 Allowable amount per child : R100.00 : R19697.65

Actual amount spent per child : R100.00 The actual amount spent was : R23000.00

Total for 4 orphanages was : R73173.60 Press any key to continue . . .

QUESTION 5:

void functions with different types and numbers of parameters

We give the solution in several steps but you had to submit the program and output of 5c only. Question 5a: Three reference parameters

A correct program is given below. All three parameters are passed with reference (note the &s in the function header), thus the values that are assigned to them in the function will be available in the main function when control returns there. Inside the do..while loop a value is input for shelfStay. The value has to bigger than 0 and as long as shelfStay is less than 0, the loop is repeated. Program code:
// Assignment 2 Question 5a

17 #include <iostream> using namespace std; // The required function inputAndValidate should be inserted here. void inputAndValidate(string & descriptionP, int & shelfStayP, float & wholesalePriceP) { cout << "Please enter description of item: "; cin >> descriptionP; do { cout << "How many days is this item expected to stay on the" << " shelf? "; cin >> shelfStayP; }while (shelfStayP < 0); cout << "Enter wholesale price for " << descriptionP << " R"; cin >> wholesalePriceP; } int main( ) { string description; int shelfStay; float wholesalePrice; inputAndValidate(description, shelfStay, wholesalePrice); cout.setf(ios::fixed); cout.precision(2); cout << description << " is expected to stay on the shelf for " << shelfStay <<" days and has a wholesale price of R" << wholesalePrice << endl; return 0; }

COS1511/202/1

Please enter description of item: Butter How many days is this item expected to stay on the shelf? 5 Enter wholesale price for Butter R14.99 Butter is expected to stay on the shelf for 5 days and has a wholesale price of R14.99 Press any key to continue . . .

Output:

Question 5b: Value parameters and reference parameters A correct program is given below. Function determinePrices has two value parameters that supply the wholesale price for an item and the number of days it is expected to stay on the shelf; and two reference parameters, namely the cash price and the credit price. The function will not make any changes to the wholesale price for an item and the number of days it is expected to stay on the shelf that is the reason why these parameter are not given to the function with reference. However, the function will change the cash price and the credit price that is the reason why the prices are given to the function with reference, so that the new values will be available in the main function. The body of the function determinePrices is straight-forward: if the item is expected to stay 7 days or less on the shelf, it is marked up with 10% over the wholesale price to determine the cash price. Items that stay longer than 7 days on the shelf are marked up with 15% over the wholesale price to determine the cash price. The credit price is then marked up with a further 2% on the cash price. Since the last two parameters in the function call are reference parameters, when control returns to the main function, the correct prices are returned.

18

Function updateDifference has three parameters: two value parameters namely the cash price and the credit price, and one reference parameter to hold the total of the differences. The function will not change the cash price or the credit price this is the reason why these two parameters are value parameters. The difference between the credit price and the cash price must be added to the total of all the differences, and the third parameter which holds the sum of these differences is therefore a reference parameter. The body of the function simply determines the difference between the credit price and the cash price and adds that to the sum of all the differences.
// Assignment 2 Question 5b #include <iostream> using namespace std; // The required functions inputAndValidate // and updateDifference should be inserted here void inputAndValidate(string & descriptionP, int & shelfStayP, float & wholesalePriceP) { cout << "Please enter description of item: "; cin >> descriptionP; do { cout << "How many days is this item expected to stay on the" << " shelf? "; cin >> shelfStayP; }while (shelfStayP < 0); cout << "Enter wholesale price for " << descriptionP << " R"; cin >> wholesalePriceP; } void determinePrices(int shelfStayP, float wholesalePriceP, float & cashPriceP, float & creditPriceP) { if (shelfStayP <= 7) cashPriceP = 1.1 * wholesalePriceP; else cashPriceP = 1.15 * wholesalePriceP; creditPriceP = 1.02 * cashPriceP; } void updateDifference(float cashPriceP, float creditPriceP, float & totalOfDifferencesP) { float difference = creditPriceP - cashPriceP; totalOfDifferencesP += difference; } int main( ) { string description; int shelfStay; float wholesalePrice, cashPrice, creditPrice, totalOfDifferences; // initialise total totalOfDifferences = 0; inputAndValidate(description, shelfStay, wholesalePrice); determinePrices(shelfStay, wholesalePrice, cashPrice, creditPrice); updateDifference(cashPrice, creditPrice, totalOfDifferences);

Program code:

19 cout.setf(ios::fixed); cout.precision(2); cout << "The cash price for " << description << " << cashPrice << " and the wholesale price is << wholesalePrice << endl; cout << "The total of the differences between the << " prices is now R " << totalOfDifferences return 0; }

COS1511/202/1

is R" R" cash and credit" << endl;

Please enter description of item: Butter How many days is this item expected to stay on the shelf? 5 Enter wholesale price for Butter R14.99 The cash price for Butter is R16.49 and the wholesale price is R14.99 The total of the differences between the cash and credit prices is now R 0.33 Press any key to continue . . .

Output:

Question 5c:

Final version

A correct program and its output are given below. The main function now contains a loop over the six items. When the loop is exited, the average price difference between the credit and cash prices is calculated and displayed.
// Assignment 2 Question 5c #include <iostream> using namespace std; const int NR_ITEMS = 6; // The required functions inputAndValidate, determinePrices // and updateDifference should be inserted here void inputAndValidate(string & descriptionP, int & shelfStayP, float & wholesalePriceP) { cout << "Please enter description of item: "; cin >> descriptionP; do { cout << "How many days is this item expected to stay on the" << shelf? "; cin >> shelfStayP; }while (shelfStayP < 0); cout << "Enter wholesale price for " << descriptionP << " R"; cin >> wholesalePriceP; } void determinePrices(int shelfStayP, float wholesalePriceP, float & cashPriceP, float & creditPriceP) { if (shelfStayP <= 7) cashPriceP = 1.1 * wholesalePriceP; else cashPriceP = 1.15 * wholesalePriceP; creditPriceP = 1.02 * cashPriceP; } void updateDifference(float cashPriceP, float creditPriceP, float & totalOfDifferencesP)

Program code:

20

{ float difference = creditPriceP - cashPriceP; totalOfDifferencesP += difference; } int main( ) { string description; int shelfStay; float wholesalePrice, cashPrice, creditPrice, totalOfDifferences, avgDifference; // initialise total totalOfDifferences = 0; for (int i = 0; i < NR_ITEMS; i++) { inputAndValidate(description, shelfStay, wholesalePrice); determinePrices(shelfStay, wholesalePrice, cashPrice, creditPrice); updateDifference(cashPrice, creditPrice, totalOfDifferences); cout.setf(ios::fixed); cout.precision(2); cout << "The cash price for " << description << " is R" << cashPrice << " and the credit price is R" << creditPrice << endl; } avgDifference = totalOfDifferences / NR_ITEMS; cout << "The average price difference between the cash and credit" << " prices is R" << avgDifference << endl; return 0; }

Please enter description of item: Butter How many days is this item expected to stay on the shelf? 5 Enter wholesale price for Butter R14.99 The cash price for Butter is R16.49 and the credit price is R16.82 Please enter description of item: Milk How many days is this item expected to stay on the shelf? 3 Enter wholesale price for Milk R16.99 The cash price for Milk is R18.69 and the credit price is R19.06 Please enter description of item: Bread How many days is this item expected to stay on the shelf? 2 Enter wholesale price for Bread R6.75 The cash price for Bread is R7.43 and the credit price is R7.57 Please enter description of item: Salami How many days is this item expected to stay on the shelf? 12 Enter wholesale price for Salami R32.88 The cash price for Salami is R37.81 and the credit price is R38.57 Please enter description of item: Wine How many days is this item expected to stay on the shelf? 39 Enter wholesale price for Wine R55.49 The cash price for Wine is R63.81 and the credit price is R65.09 Please enter description of item: Newspaper How many days is this item expected to stay on the shelf? 1 Enter wholesale price for Newspaper R5.99 The cash price for Newspaper is R6.59 and the credit price is R6.72 The average price difference between the cash and credit prices is R0.50

Output:

21 Press any key to continue . . ..

COS1511/202/1

QUESTION 6:

Function calls

Tbere are MANY correct answers. We give a few only. Question 6a Example 1:
int age; bool smoker; bool toInsure; toInsure = insure(age,smoker);

Example 2:
bool smoker; bool toInsure; toInsure = insure(30,smoker);

Example 3:
int age; bool toInsure; toInsure = insure(age,true);

Question 6b Example 1:
int min; int max; int count; float estimate; estimate = estimateTotal(min,max,count);

Example 2:
int count; float estimate; estimate = estimateTotal(10,1000,count);

Example 3:
float estimate; estimate = estimateTotal(10,1000,5);

Note that the function headers of both the functions in question 6a and 6b contain value parameters. The value of the variable is sent to the function, so all above examples are valid function calls

Question 6c

22

int year; int month; int day; string century; getDate(year,month,day,century);

Question 6d
char flag; float price; float time; char calcInterest; calcInterest = interest(flag, price, time);

Note that the function headers in question 6c and 6d contain reference parameters, so the address of the variables are sent to the function. The following 2 function calls, one for question 6c and one for question 6d, are therefore invalid, because they send values for some of the reference parameters:
getDate(2011,9,12,century); calcInterest = interest(c, 102.96, time);

QUESTION 7:

Decide yourself

A correct program and its output are given below. We followed the conventions of the Study Guide in deciding on the types of the functions and parameters. Let us consider each function separately: Function inputAndValidate: Here we have a void function because input is done in the function. There are two parameters, namely hours for the time in hours, and minutes for the time in minutes. These parameters are given to the function with reference (note the &), since their (input) values have to be available in the main function. The body of the function consists of the input of these two values. The hours must be between 0 and 24, and the minutes must be between 0 and 59. We use a two do while loops to check this. The user has to enter the value again if it is incorrect. If a value of 24 has been input for the hour, the value of the minutes is made 0, regardless of what value the user has entered for the minutes. Function convertToMinutes: This is a value-returning function because no input or output is done and one value only is returned. The return type is int. There are two value parameters, namely hourP and minutesP. These values are not changed. The body of the function consists of a statement to convert the time given in hours and minutes to time in minutes. Function convertBackToTime: This is a void function because no input or output is done and two values only are returned. There is one value parameter, namely allMinutesP and two reference parameters, namely hoursP and minutesP (note the &). The value parameter allMinutesP is not changed. The body of the function consists of a statement to convert the value of allMinutesP (time in minutes) to time in hours (hoursP) and minutes (minutesP). Function calcCharge: This is a value-returning function because no input or output is done and one value only is returned. The return type is float. There are two value parameters, namely hoursP and minutesP. The values of the value parameters are not changed. The body of this function consists of calculating the fee which should be paid by the customer. The fee is based on the time that the car was parked, which is indicated by hoursP and minutesP. If a car was parked for less than 3 hours, a minimum fee of R7 is charged. This is shown below: if (hoursP < MINIMUM_HOURS) fee = MINIMUM_CHARGE;

23

COS1511/202/1

Thereafter a fee of R1.50 per hour or part of an hour is charged in addition to the minimum fee, as can be seen in the else part of the above if statement, shown below: else { fee = MINIMUM_CHARGE + (hoursP - MINIMUM_HOURS) * FEE_PER_HOUR; if (minutesP > 0) fee +=FEE_PER_HOUR; } Function main: Firstly the necessary variables are declared and the total of all the charges initialized to 0. Then the program loop over the number of customers (10) and for each customer, calls inputAndValidate twice, once to read the entrance time and again to read the exit time. Then both the entrance and exit times are converted to minutes with two calls to convertToMinutes. If the exit time in minutes is greater than the entrance time in minutes, the parked time is calculated as follows: minutesParked = exitTimeInMins - entranceTimeInMins; The parked time is then converted back to time in hours and minutes with convertBackToTime, the fee due is calculated with calcCharge, the receipt is displayed for the customer and the charge is added to the total of all the charges. Finally, the total of all the charges is displayed.
//Assignment 2 Question 7 #include <iostream> using namespace std; const const const const const int MINUTES_PER_HOUR = 60; int MINIMUM_HOURS = 3; float MINIMUM_CHARGE = 7.00; float FEE_PER_HOUR = 1.50; int NR_CUSTOMERS = 10;

//function inputAndValidate void inputAndValidate(int & hoursP, int & minutesP) { cout << "Enter time as hours and minutes. "; do { cout << "Hours: "; cin >> hoursP; }while ((hoursP > 24) || (hoursP < 0)); do { cout << "Minutes: "; cin >> minutesP; }while ((minutesP > 59) || (minutesP < 0)); if ((hoursP == 24) && (minutesP > 0)) { cout << "Minutes must be 0"; minutesP = 0; } } int convertToMinutes(int hoursP, int minutesP) { return hoursP * MINUTES_PER_HOUR + minutesP; } void convertBackToTime(int allMinutesP, int & hoursP, int & minutesP) { hoursP = allMinutesP / MINUTES_PER_HOUR;

24

minutesP = allMinutesP % MINUTES_PER_HOUR; } float calcCharge(int hoursP, int minutesP) { float fee; if (hoursP < MINIMUM_HOURS) fee = MINIMUM_CHARGE; else { fee = MINIMUM_CHARGE + (hoursP - MINIMUM_HOURS) * FEE_PER_HOUR; if (minutesP > 0) fee +=FEE_PER_HOUR; } return fee; } int main() { int entranceHour, entranceMinutes; int exitHour, exitMinutes; int entranceTimeInMins, exitTimeInMins, minutesParked; int parkedHours, parkedMinutes; float charge; float totalCharges = 0; for (int i = 1;i <= NR_CUSTOMERS; i++) { cout << "What time did you enter the parking garage?" << endl; inputAndValidate(entranceHour, entranceMinutes); cout << "What time did you exit the parking garage?" << endl; inputAndValidate(exitHour, exitMinutes); entranceTimeInMins = convertToMinutes(entranceHour, entranceMinutes); exitTimeInMins =convertToMinutes(exitHour, exitMinutes); if (exitTimeInMins > entranceTimeInMins) { minutesParked = exitTimeInMins - entranceTimeInMins; convertBackToTime(minutesParked, parkedHours, parkedMinutes); charge = calcCharge(parkedHours, parkedMinutes); cout.setf(ios::fixed); cout.precision(2); cout << "\nEntrance time: " << entranceHour << "h" << entranceMinutes << "\t"; cout << "Exit time: " << exitHour << "h" << exitMinutes; cout << "\nParked time: " << parkedHours << "h" << parkedMinutes << endl; cout << "Charge: R" << charge << endl << endl; totalCharges +=charge; } else cout << "Invalid exit time"<<endl; } cout << "Total of all the charges: R" << totalCharges << endl; return 0; }

Output:

25 What time did Enter time as Minutes: 30 What time did Enter time as Minutes: 23 you enter the parking garage? hours and minutes. Hours: 9 you exit the parking garage? hours and minutes. Hours: 13 Exit time: 13h23

COS1511/202/1

Entrance time: 9h30 Parked time: 3h53 Charge: R8.50 What time did Enter time as Minutes: 00 What time did Enter time as Minutes: 59

you enter the parking garage? hours and minutes. Hours: 8 you exit the parking garage? hours and minutes. Hours: 12 Exit time: 12h59

Entrance time: 8h0 Parked time: 4h59 Charge: R10.00 What time did Enter time as Minutes: 12 What time did Enter time as Minutes: 13

you enter the parking garage? hours and minutes. Hours: 10 you exit the parking garage? hours and minutes. Hours: 13 Exit time: 13h13

Entrance time: 10h12 Parked time: 3h1 Charge: R8.50 What time did Enter time as Minutes: 00 What time did Enter time as Minutes: 12

you enter the parking garage? hours and minutes. Hours: 10 you exit the parking garage? hours and minutes. Hours: 12 Exit time: 12h12

Entrance time: 10h0 Parked time: 2h12 Charge: R7.00 What time did Enter time as Minutes: 01 What time did Enter time as Minutes: 14

you enter the parking garage? hours and minutes. Hours: 7 you exit the parking garage? hours and minutes. Hours: 17 Exit time: 17h14

Entrance time: 7h1 Parked time: 10h13 Charge: R19.00 What time did Enter time as Minutes: 18 What time did Enter time as Minutes: 33

you enter the parking garage? hours and minutes. Hours: 6 you exit the parking garage? hours and minutes. Hours: 16 Exit time: 16h33

Entrance time: 6h18

26

Parked time: 10h15 Charge: R19.00 What time did Enter time as Minutes: 15 What time did Enter time as Minutes: 04 you enter the parking garage? hours and minutes. Hours: 14 you exit the parking garage? hours and minutes. Hours: 16 Exit time: 16h4

Entrance time: 14h15 Parked time: 1h49 Charge: R7.00 What time did Enter time as Minutes: 11 What time did Enter time as Minutes: 45

you enter the parking garage? hours and minutes. Hours: 13 you exit the parking garage? hours and minutes. Hours: 17 Exit time: 17h45

Entrance time: 13h11 Parked time: 4h34 Charge: R10.00 What time did Enter time as Minutes: 27 What time did Enter time as Minutes: 55

you enter the parking garage? hours and minutes. Hours: 11 you exit the parking garage? hours and minutes. Hours: 14 Exit time: 14h55

Entrance time: 11h27 Parked time: 3h28 Charge: R8.50 What time did Enter time as Minutes: 55 What time did Enter time as Minutes: 47

you enter the parking garage? hours and minutes. Hours: 8 you exit the parking garage? hours and minutes. Hours: 15 Exit time: 15h47

Entrance time: 8h55 Parked time: 6h52 Charge: R13.00

Total of all the charges: R110.50 Press any key to continue . . .

Unisa 2011

You might also like