Chat with us, powered by LiveChat Intro to C++ | Writedemy

Intro to C++

Intro to C++

ASSIGNMENT 2 – WRITTEN (PRACTICAL) ASSIGNMENT

SUBMISSION: Eitherby post orelectronically via myUnisa as one WORD or pdf document. Assignments may not be submitted by fax or e-mail. Please use single line spacing in the Word or pdf document that you submit.

Please note that we automatically give five days extension for Assignment 2.It will be toyour own advantage to check after a few days whether the assignment has been registered on the system. If you have not completed the assignment by the extension date, submit whatever you have completed – you will get marks for everything that you have done.

If myUnisa is off-line when you want to submit the assignment, you need not contact us, because we will be aware of it. Simply submit it as soon as myUnisa is available again.

DUE DATE 3 April
EXTENSION There is an automatic extension until 8 April.
You do not need to phone or send an e-mail to
request automatic extension.
TUTORIAL MATTER Study Guide, Lessons 1 – 22
UNIQUE NUMBER 831984
WEIGHT OF CONTRIBUTION TO 70%
SEMESTER MARK

IS YOUR SOFTWARE INSTALLED?

Look at ‘Troubleshooting’ under ‘Using the software’ in file index.html on Disk2013.

If you struggle to install the software, you may contact the technical assistants of the School of Computing to assist you – 012-429-8860/1/2/3/4/5/6/7.

PLEASE TURN OVER

45

Question 1: LOOPING

Question 1a

Suppose we want to input and validate the age of students that qualify for an internship, as well as the final mark obtained for the examination, in awhile loop. To qualify, the student should be younger than 30 with a final mark of more than 65%. The variable names areage andfinalMarkrespectively. Complete the whileloop below. You only have to write down thecompleted while loop.

cout << “Enter age: “; cin >> age;

cout << “Enter final mark for exam: “; cin >> finalMark;

while (…………………) //complete the condition

{

//complete the while loop

}

Question 1b

Write a program that contains the followingfor loop. Discuss the output of the program, by explaining what the purpose of the program is. Execute the program and submit your program as well as the output.

Hint:Use variable diagrams to trace the program to help you understand what it does.

for (int i = 5; i > 0; i–)
{
for (int j = 0; j < i-1; j++)
cout << ‘ ‘;
for (int k = i; k <= 5; k++)
cout << ‘*’;

cout << endl;

}

46

COS1511/101

Question 1c

Include thefor loop below in a small program and complete the program. The loop should be executed 10 times. Do not change thefor loop below. Compile and run your program to see

for yourself that it works. You do not have to submit this program and output.for (int i = 1; i <= n; i++)

if (i < 5 && i != 2) cout << ‘X’;

Now convert thefor loop into awhile loop and add any variable initialisations that you think are necessary. Compile and run your program and submit only the program containing thewhileloop and its output.

Question 1d

The following code is supposed to calculate the product of the numbers 2 through 5. That is, it should calculate the value of 2 x 3 x 4 x 5, which is 120. However, there is a logical error in the code. Explain what the output of the code below will be. Then write a small program including the code below and make the necessary changes to fix the code so that it displays what it is intended to display. Ensure that your program works correctly. Only submit the program, not the output.

Hint:Use variable diagrams to trace the program to help you find the logical error.

int next = 2, product = 1; while (next <= 5)

{

next++;

product = product * next;

}

cout << “The product of 2 though 5 is ” << product << endl;

Question 2: NESTED LOOPS

Question 2a

To track the numbers of three types of birds of prey, bird-watchers annually perform a count of the number of eggs in these birds’ nests during a specific week in a certain district. This data is entered into the program below and the total number of eggs counted for each type of bird is calculated.

A bird-watcher’s report for one nest consists of a character indicating which bird’s nest she saw (E for an eagle, O for an owl, and V for a vulture), and the number of eggs in the nest. To indicate the end of her report, a bird watcher will enter an X.

The program has the following structure:

• Totals for the number of eggs for each of the different types of birds are initialized to 0.

• A prompting message to input the number of bird watchers.

• A for loop to input the data each bird watcher has collected.

• Inside thefor loop, ado while loop to input and process the data collected by one bird watcher.

47

• Inside thedo while loop aswitch statement is used to calculate the number of eggs for each type of bird. The default option, which does nothing, is used when an X is entered.

• The do while loop is exited when an X is entered for the type of bird.

• The totals for the number of eggs of each type of bird the bird watcher has seen, is displayed.

• When thefor loop is exited, the three grand totals for the three types of bird’s eggs are displayed.

To help you we give the following framework:

#include <iostream> #include <cstdlib> using namespace std; int main()

{

int totNrVultureEggs, totNrEagleEggs, totNrOwlEggs, nrEggs, nrVultureEggs, nrEagleEggs, nrOwlEggs, nrBirdWatchers;

char bird;

// initialize grand totals for number of eggs for each type of bird

cout << “How many bird watchers took part in the study?”; cin >> nrBirdWatchers;

// loop over number of bird watchers for ( ; ; )

{

// initialize totals for number of eggs for each type of bird

// this bird watcher saw

nrVultureEggs = 0;

nrEagleEggs = 0;

nrOwlEggs = 0;

cout << ” Enter data for bird watcher ” << i +1 << “:” << endl;

//loop over bird watchers

48

COS1511/101

while ( )

{

// complete the loop

};

cout << “Bird watcher ” << i + 1 << ” saw ” << nrVultureEggs; cout << ” vulture eggs, ” << nrEagleEggs << ” eagle eggs and “; cout << nrOwlEggs << ” owl eggs ” << endl;

// increment grand totals for eggs

}

// display results

cout << ” Total number of vulture eggs: ” << totNrVultureEggs; cout << ” Total number of eagle eggs: ” << totNrEagleEggs; cout << ” Total number of owl eggs: ” << totNrOwlEggs;

return 0;

}

Run your program with the input given below and submit printouts of the program and output. (We write the data of each bird watcher in one line, but you will possibly enter the values on separate lines. There were three bird watchers.)

3

E2 O1 V2 E1 O3 X0

V2 V1 O1 E3 O2 E1 X0

V2 E1 X

Question 2b

In this question we describe the problem and then you have to decide yourself how you are going to tackle it:

Four experiments are performed, each consisting of five test results. The results for each experiment are given in the following list. Write a program using a nested loop to compute and

49

display the average of the test results for each experiment. Display the average with a precision of two digits after the decimal point.

1st experiment results: 23.2 31 16.9 27 25.4
2nd experiment results: 34.8 45.2 27.9 36.8 33.4
3rd experiment results: 19.4 16.8 10.2 20.8 18.9
4th experiment results: 36.9 39 49.2 45.1 42.7

Use the input provided in the given list, and submit printouts of your program and its output.

Question 3: void FUNCTIONS

A function namedprintDescription (with no parameters) displays the following message:

***************************************************

This program inputs two numbers (pay rate and hours)

and outputs net pay.

***************************************************

Another function,computePaycheck displays the net pay of an employee. The function takes a rate and time and multiplies them to compute the gross pay of an employee. It then calculates and displays the net pay by subtracting 15% from the gross pay. The function has two value parameters rate and time (hours worked).

A main program inputs a floating point value (payRate) and an integer value(hours). It displays the description of the program by calling the functionprintDescription. The program then calls the functioncomputePaycheck to calculate and display the net pay.

Sample run:

Welcome to the Pay Roll

***************************************************

This program takes two numbers (pay rate and hours) and outputs net pay.

***************************************************

Please input the pay per hour 9.50

Please input the number of hours worked 40

The net pay is R 323

We hope you enjoyed this program

50

COS1511/101

Question 3a

Write the functionsprintDescription andcomputePaycheck as well as the main program.

Question 3b

Change the program so that the net pay is displayed in the main program instead of functioncomputePaycheck.

Question 4: FUNCTIONS WITH DIFFERENT RETURN TYPES AND ONE OR MORE VALUE PARAMETERS

Question 4a

Write a function namedtax() that accepts an amount of Rands and a tax rate as formal parameters and returns the tax due on the amount. For example, if the values100.00 and0.06are passed to the function, the value returned should be 6.00,which is 100.00 * 0.06.

Include thetax() function in a working program. Themain() function should input the values, correctly calltax() and display the value returned by the function, all with appropriate messages.

Question 4b

This question builds upon Activity 17 in the guide. The program chooses the number to be guessed by selecting an integer at random in the range 1 to 1000. The program then displays the following:

I have a number between 1 and 1000.

Can you guess my number?

Please type your first guess.

The player then types a first guess. The program responds with one of the following:

→ Excellent! You guessed the number! Would you like to play again (y or n)?

→ Too low. Try again.→ Too high. Try again.

If the player’s guess is incorrect, your program should loop until the player finally gets the number right. Your program should keep telling the playerToo high orToo low to help the player “zero in” on the correct answer.

Your program should also count the number of guesses the player makes. If the number is 10 or fewer, print”Either you know the secret or you got lucky!” If the player guesses the number in 10 tries, then print “Ahah! You know the secret!” If the player makes more than 10 guesses, then print”You should be able to do better!” Why should it take no more than 10 guesses? Well, with each “good guess” the player should be able to eliminate half of the numbers.

51

A sample run:

I have a number between 1 and 1000. Can you guess my number?

Please type your first guess. ? 500

Too high. Try again. ? 250

Too low. Try again. ? 375

Too high. Try again. ? 313

Too low. Try again. ? 344

Too low. Try again. ? 360

Too high. Try again. ? 352

Too high. Try again. ? 348

Too low. Try again. ? 350

Too low. Try again. ? 351

Excellent! You guessed the number! You have made 10 guesses!

Ahah! You know the secret!

Would you like to play again (y or n)? n

Your program will consist of three functions.

• The first functiongetGuess return an integer that represents the user’s guess which is read from the keyboard.

• The second functionisCorrect takes two value parameters, thevalueGuessed and therandomNumber and compare the two values. IfvalueGuessed equalsrandomNumber,the function returns true. IF valueGuessedis less than randomNumber,the function displays “Too low. Try again”,else valueGuessedis greater thanrandomNumber and displays”Too high. Try again”. In both casesfalseis returned.

• The last functionanalyzeCount takes one value parameter, the number of guesses. It then displays the number of guesses as well as an appropriate message (one of the three messages below) depending on the value of the number of guesses:

→ Either you know the secret or you got lucky!→ Ahah! You know the secret!

→ You should be able to do better!

52

COS1511/101

Question 5: FUNCTIONS WITH DIFFERENT RETURN TYPES AND PARAMETERS

Write a program that will calculate and print pay slips. User inputs are the name of the employee, the number of hours worked and the hourly pay rate. You have to declare three functions.

a) one for input;

b) one to calculate the employee’s pay; and

c) one to print the payslip.

The input function has to input the name of the employee, the number of hours worked and the hourly pay rate into the variablestheEmployee,theHoursWorked andthePayRate. The variableemployee is a string and the other two variables are of typefloat. As the values oftheEmployee, theHoursWorkedand thePayRatewill be changed in this function, referenceparameters need to be used.

The calculation function will receive two parameters that represent the number of hours worked and the hourly pay rate, do the calculation and return the pay for the employee. An employee who has worked more than 40 hours, is paid 1.5 time the hourly pay rate for each hour of overtime. As the parameters are not changed in the function, they should be value parameters. The function should return a float value which represents the pay.

The output function has to display the name of the employee, the number of hours worked, the number of overtime hours and the hourly pay rate entered by the user as well as the employee’s pay. For example:

Pay slip for Harry Matsipe

Hours worked: 43.5 hours

Overtime hours: 3.5

Hourly pay rate: R125.35

Pay: R5672.09

Themain function includes afor loop that allows the user to repeat the calculation of a pay slip for five employees. We give themain function below. You must submit the three functions you have developed as well as output for repeating the loop five times with the following input data:

Harry Matsipe 43.5 125.35

Ellen Malan 39.4 112.75

Joey Rashdien 40 120.45

Mpho Bopape 41.2 123.60

Veli Singh 39.7 135.30

53

int main( )

{

string theEmployee; float theHoursWorked; float thePayRate;

int thePay;

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

{

getData(theEmployee, theHoursWorked, thePayRate); thePay = calculatePay(theEmployee, theHoursWorked,

thePayRate); printPaySlip(theEmployee, theHoursWorked,

thePayRate, thePay);

}

return 0;

}

Question 6: FUNCTION CALLS

In this question you should write down short answers only. Look at the following program and then answer the questions that follow.

Hint:Study the function header carefully before answering the question.

PROGRAM

1. #include <iostream>

2. #include <string>

3. using namespace std;

4. void processData(string studentNrP, string nameP, int & markP,

int & nrPassedP)

5. {

6. if (markP == 48) || (markP == 49)

7. markP = 50;

8. if (markP == 74)

9. markP = 75;

54

COS1511/101

10. if (markP >= 50)

11. ++nrPassedP;

12. cout << “Final mark for student” << studentNrP << string nameP

<< ” is ” << markP << endl;

13. }

14. int main()

15. {

16. string name, studentNr;

17. int mark;

18. int nrPassed = 0;

19. cin >> name >> studentNr >> mark;

20. processData(name, studentNr, mark, 0);

21. studentNr = “8954321”;

22. name = “Mr. John Smith”;

23. processData(name, studentNr, 74, nrPassed );

24. processData(“Ms. Beauty Sithole”,”4327834″ , mark, nrPassed);

25. return 0;

26. }

Question 6a

Is the function call in line 20 a valid function call? Give reasons for your answer.

Question 6b

Is the function call in line 23 a valid function call? Give reasons for your answer.

Question 6c

Is the function call in line 24 a valid function call? Give reasons for your answer.

55

Question 6d

Consider the following variable definitions and function call:

string customer = “Anna Elias”; float amountDue;

float timeSpent = 72.56; float cost = 1534.78;

determineFee(customer, amountDue, cost, 200.53);

Consider the two function headers below. For each header, say if you think the header for functiondetermineFee is a valid header, and give reasons for your answer:

1. void determineFee (string customerP, float & amntDueP,

float & costP, float & timeSpentP); 2. void determineFee (string customerP, float & amntDueP,

float & costP, float timeSpentP);

Question 7: VARIABLE DIAGRAMS REVISITED

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 {

56

COS1511/101

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 }

57

Our website has a team of professional writers who can help you write any of your homework. They will write your papers from scratch. We also have a team of editors just to make sure all papers are of HIGH QUALITY & PLAGIARISM FREE. To make an Order you only need to click Ask A Question and we will direct you to our Order Page at WriteDemy. Then fill Our Order Form with all your assignment instructions. Select your deadline and pay for your paper. You will get it few hours before your set deadline.

Fill in all the assignment paper details that are required in the order form with the standard information being the page count, deadline, academic level and type of paper. It is advisable to have this information at hand so that you can quickly fill in the necessary information needed in the form for the essay writer to be immediately assigned to your writing project. Make payment for the custom essay order to enable us to assign a suitable writer to your order. Payments are made through Paypal on a secured billing page. Finally, sit back and relax.

Do you need an answer to this or any other questions?

About Writedemy

We are a professional paper writing website. If you have searched a question and bumped into our website just know you are in the right place to get help in your coursework. We offer HIGH QUALITY & PLAGIARISM FREE Papers.

How It Works

To make an Order you only need to click on “Order Now” and we will direct you to our Order Page. Fill Our Order Form with all your assignment instructions. Select your deadline and pay for your paper. You will get it few hours before your set deadline.

Are there Discounts?

All new clients are eligible for 20% off in their first Order. Our payment method is safe and secure.

Hire a tutor today CLICK HERE to make your first order