Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
CS111 Lab Manual 2015 v4.0
July 19, 2015
1 Introduction
CS111 is an introductory programming course. It uses the C++ programminglanguage. This documents describes the labs. This is version v4.0. Pleasecheck for updates regularly.
The labs this year differ significantly from last years labs. This means thatstudent who repeat the course cannot get ”cross credit” for these labs.
1.1 Lab fundamentals
The labs for CS111 will take 2 hours a week. They will start in the secondweek of the semester. You will have to sign up for a tutorial in the first week.You only have to sign up for one lab time.
The labs take two hours. The first hour will consist (usually) exercises thatrecapitulate the new material covered in lectures. In the second hour you willhave time to apply new material to your own problem. This problem will beassigned to you in week 2. You will be assigned a problem for the first half of thecourse - before the mid-semester break - and a second problem for the secondhalf. In each week you have the opportunity to extend your program and workon your problem. At the end of the each half of the semester these programswill be assessed. This assessment forms the main part of your lab mark. Thereare other weekly activities that will contribute to you lab mark. These rangefrom choosing a lab partner, to submitting test cases.
1.2 Group work
All students should work in groups of two. Groups cannot be larger, two is themaximum. Working alone is possible, but it is discouraged. Programming is ateam sport, and you will learn a lot by trying to explain to a peer what youwant to do.
You are encouraged to talk to other students, the tutors or the lecturer forfeedback, advice, tips and clarification. Use the Moodle forum if possible.
You are however strongly discouraged to just copy and thus plagiarize aprogram from other students. First, because it won’t teach you anything. Youare not in this course to pass it, you are in this course to learn programming.
1
Second, your own problem is different from the problems other students inyour lab. Their program will be a bad solution to your problem.
Thirdly, if you get caught plagiarizing in the assignment you will get zeromarks. Repeated plagiarism will incur additional disciplinary actions. Get usedto do your own work.
Despite these warning about plagiarism, please keep in mind that you arevery much encouraged to talk to your peers and to help each other. As long asyou do your own work in the end. So, tell them how you did it, or ask themhow they did theirs.
1.3 Marking
The lab component will be marked out of 100. There are three ways to earnmarks:
1. Demonstrate your program to the tutor. In the first 7 weeks youwill work on one programming problem, in the second 7 weeks on another.You have to upload your program, and then discuss it in person with yourtutor. The tutor will mark it out of 10. This sums up to a maximum of40 marks.
2. Moodle activities. These are small activities you are asked to do inthe weeks in which you do not have to show your program. You will get5 marks for completing each of these (regardless of whether you do themwell). You can earn up to 50 marks for this.
3. Participation. During the lab you will get the opportunity to presenteither your, or your peers work to class. You will earn 5 marks for eachtime you stand in front of the class. Every student should at least do thistwice (and earn 10 marks) but there is no limit, other than the number oflabs and number of presentation exercises per lab.
2
1.4 Lab exercises
There are five different types of lab exercises. Some require you to program, butthere are other exercises too. You should learn that hacking away on a keyboardis only a small part of what it takes to create a good program.
Programming Exercise 1.4.1 –In these exercises you are required to work as a pair of two on a programmingproblem. It is very important that you know your material. The time given forthese tasks is plenty to complete the task, but too little for you to read up onthe textbook and notes. You can ask the tutor for help.
Peer Exercise 1.4.2 –In this activity you will be asked to give feedback to another group of students,usually on their program. You are asked to check if it works, and if not youcan help them improve it. They are in turn asked to give you feedback on yourprogram.
Paper Exercise 1.4.3 –For this exercise you do not need a computer, but you need pen and paper.And brains. These exercises ask you think about a programming problem andmake a plan or design, or answer questions on a given program. Don’t touchyour computer for a while. Except maybe for reading the exercise.
Presentation Exercise 1.4.4 –This activity will ask a student to either present their own program, or theprogram of a peer. You will be rewarded with 5 marks towards your lab marks.Only a handful of students will get the chance to present in any single lab, butover the course the weeks there will be plenty of opportunity.
Online Exercise 1.4.5 –This activity requires every student to complete a task on Moodle. Usually it isa simple task that related to the weekly lab and your programming task. Youwill be collecting marks for completing this.
3
1.5 Summary
• Labs start in week 2.
• Pick a lab time in week 1.
• You will be assigned a programming problem for each half.
• You have to discuss you program in person with the tutor to get marks.
• You have to complete the weekly activities.
• You get marks for participation.
• Discuss your program, ask advice, but don’t plagiarize.
4
Week Topic Weekly Task Marks1 Introduction No lab. Complete Questionnaire. (Moodle) 52 Standard I/O Forming a group of two and make welcome message(Moodle) 53 Variables and Arithmetic Define inputs (Moodle). 54 If statements Upload screenshot (Moodle) 55 Booleans Define 5 test cases (Moodle) 56 Loops Demonstrate program (Tutor) 107 Nested Loops Demonstrate program (Tutor) 10
8 Functions Self assessment (Moodle) 59 Functions Submit design (Moodle) 510 Arrays Submit design (Moodle) 511 Arrays Demonstrate program (Tutor) 1012 Pointers Submit design (Moodle) 513 Structs Demonstrate program (Tutor) 1014 File I/O Self assessment (Moodle) 5
Table 1: Lab schedule for CS111
2 Weekly Lab Descriptions
This section will describe the weekly labs. See the Table 1 for a schedule,including the topics of the week, the topic of the lab and the task you are askedto complete. The column marks states how many marks you can get at mostfor completing the task.
2.1 Week 1
In week 1 there will be no labs. In this week you will have to go on Moodleand select a lab time. Also you will have to complete a questionaire. You willbe awarded 5 points for this activity.
5
2.2 Week 2
In this week you will have to attend your first lab. This lab will be used tointroduce you to DEV-C++, and you will write the first programs. Also, youwill have to form groups of two. Both you and your partner have to be fromthe same lab, i.e. the same time and location. You will be awarded 5 points forforming a team. You will be assigned a project for the first half of the semester.
Programming Exercise 2.2.1 – Introduction to the IDE (5 minutes)
In this exercise you are asked to start the IDE once and close it. The reasonis to make sure that is configured correctly once. Closing it ensures that theconfigurations are stored for future use.
1. Go to START and search for Dev-C++
2. Click on ”Next” or ”Yes” until the program completely starts
3. Exit the program.
Programming Exercise 2.2.2 – Hello World (20 minutes)Every programmer in the world has written the Hello World program. Thisexercise will give you practice on writing your own Hello World program fromscratch, and get it compiled and have it run.
1. Start Dev-C++. Close it if its already open, and start it again.
2. Create a new source file and save it in your as hello. Remember you donthave to add the .cpp extension. Dev will automatically add it to the filename.
3. Delete all the code thats in the text editor window.
4. Instead type the following C++ code. Dont worry about the details ofthe program. You should at least be able to write it exactly as it is:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
cout << "Hello World" << endl;
cout << "This is my first C++ program" << endl;
system("PAUSE");
return 0;
}
6
5. Note: It is a good practice to keep saving your work while you writingprograms. And before you compile and execute a program, you shouldalways form a habit of saving your work. Just click on or press CTRL+S.
6. Once you have entered your source code, compile it.
7. If any errors are reported, see the compile error pane by clicking thecompiler tab. Double-clicking any error will take you to the line of yourprogram which contains the error. See if you can fix them.
8. If there are no errors, go ahead and execute your program.
Presentation Exercise 2.2.3 – Hello World to all (5 minutes)One student group gets the chance to present their ”Hello World” program.They should
1. Discuss problems they encountered.
2. Show how to compile the program.
3. Show how to run it.
The group that present will be awarded 5 marks. If there are no volunteers, thetutor will nominate a student or group.
Programming Exercise 2.2.4 – Welcome message (20 minutes)You should will be assigned a project from Appendix A by the tutor. You willwork on it for the next seven weeks. Each week you will use what you’ve learnedin class to extend it and make it better.
In this week all you have to do is to come up with a welcome message. Writea program that prints a the welcome message to screen. It should explain inplain English what it does, and maybe print a list with prices. If you haveproblems with formatting or compiling ask the tutor. Or your neighbor. Savethis program in a file called projectA01.cpp and take it with you. You willcontinue working on this program in the next few weeks.
Peer Exercise 2.2.5 – Share your Welcome Message (10 minutes)You have to pair up with another group and in turn discuss the two programsyou have been working. This is the time to ask the other group for advice. Youshould address the following questions:
• Does the program compile, and if not why not?
• Does the welcome message explain what the program is going to do?
• Does the message match the problem description in the Appendix?
• Does the welcome message look professional and good?
7
Presentation Exercise 2.2.6 – Present your Welcome Message (10minutes)This is the opportunity for at least two groups to show their welcome messageto the the other students. You should do the following:
• Explain what your problem is in your own words.
• Compile the program, and show how to run it.
• Explain how the code relates to the output.
The remainder of the lab can be used to continue working on the Welcomemessage, and to ask the tutor for help.
Online Exercise 2.2.7 – Task of the week
Write a program that writes a nice welcome message for your problem (Theone from the appendix). You are free to format it as you want, and call it whatyou want. Just make sure that it looks professional.
Once you run it, copy and paste the output into Moodle. In Windows right-click on the menu bar, select Edit>Select All, then right-click on the menu baragain and select Edit>Copy. You can then paste the output into your browser.
You will be awarded 5 points for completing this online task.In addition, you have to register your team and project. Go to the
weekly activities section of week 2, enter the team members and the projectyou’ve been assigned. All marks that one team member gets for the lab (notfor test or exam, of course) will eventually be also given to the team member.To do that we need to know who you work with.
8
2.3 Week 3
Programming Exercise 2.3.1 – Debugging mistakes (20 minutes)
1. Open Dev-C++ and create a new source file.
2. As usual delete all the code thats in there.
3. Save your file as studentgrades.cpp
4. Write the following code in your editor window:
#include <stdlib.h>
int main(){
cout << "\n\tGrade List for CS111" << endl;
<< "\t--------------------\n\n";
cout << "\tGoogle Smith\t\tA" << endl;
Cout << "\tJohn Pencil\t\tB" << endl
<< "\tMr. Football\t\tC" << endl;
cout << "\tJason Stone\t\tB+"
<< endl < "\tStapler Pin\t\tA+" << endl;
cout << "\tManila Folder\t\tC+" << endl cout <<
<< "\tKeyboard Hunter\t\tD" << endl;
cout << "\tSystem Speaker\t\tE" << endl;
cont << endl << \n;
system("PAUSE");
return 0;
)
5. Save and then compile the program. View the errors generated in thecompiler tab pane. Double-clicking on an error will take you to the linewhere the error occurred. Try to fix them. [Note: sometimes the linewhich is identified as having the error does not actually contain the error.There might be program statements before it that caused that line to beinvalid.
6. If you have managed to fix all the errors and run the program, show it toyour tutor.
Presentation Exercise 2.3.2 – Present the errors (10 minutes)At least two groups get the chance to fix the problems and explain what theydo to address them. Question to be asked are:
1. Which mistakes could you fix?
2. What does the error message mean?
9
3. What was the problem?
4. Did you fix the problem , or did you just make the warning go away?
Two group may be asked to show their corrected versions, and thus earn 5marks.
Programming Exercise 2.3.3 – Invitation (10 minutes)One Moodle you will find a program w3name.cpp. Extend the program suchthat, after asking for a name, it will print
Dear name,You are invited to my public lecture next Friday.
Of course, name should be the name that the user enters.
Programming Exercise 2.3.4 – Arithmetic (15 minutes)Write a program that asks the user to enter two integer numbers x an y andcomputes x ∗ y − (y + x) and prints the result to standard output.
Paper Exercise 2.3.5 – Identify you inputs (10 minutes)This is the first paper exercise this semester. For this you do not need a com-puter. If you write a program for this exercise, you are doing it wrong. Pen andpaper are the tools. Get used to the fact that it will safe you time if you sit andthink about a problem, before you attempt programming a solution.
To compute make an invitation, you need to know the name. For the arith-metic problem you need to ask for the values of x and y. Those are inputs.
Inputs can also be choices with more than two values, like: which is yourfavorite color [red/green/blue]. An ”input” corresponds to one question, or onepiece of information that you have to ask from the user. For each input you needto decide what its type is. This means, do you want the user to enter an integer,a floating point number, a single character, or a word? The corresponding typeswould then be int, double, char or string.
For your problem, identify what are the input that you need to know inorder to compute the price or reward. Ask your tutor for help if you are stuck.
Online Exercise 2.3.6 – Submit your inputsPlease upload the inputs to on Moodle. You will be awarded 5 point for com-pleting the task. If you have problems with this task, talk to your tutor.
Programming Exercise 2.3.7 – Ask your user for input (30 minutes)
Extend your program such that it can ask the user for it choices and inputs,
10
and then displays the user answers back. Similar to the invitation program thatasks for the name and then prints the an invitation.
To do this you have to do the following:
• Define input variables.
• Read from standard input.
• Write the answers back to standard output.
Presentation Exercise 2.3.8 – Present your program. (10 minutes)
At least two groups get the chance to show their program. Question to be askedare
1. Does the output look good?
2. Does the output give good and accurate information?
3. Does the code adhere to good style guidelines?
11
2.4 Week 4
Paper Exercise 2.4.1 – Macquarie Island Police (10 minutes)Note, this is a paper exercise. No need to use the computer. If you try to answerthis question by programming, then your are doing it wrong.
Macquarie Island police is controlling for speeding. The fines for speedingare computed as follows.
• If the speed is 50km/h or above, you get a base fine of $50.
• If the speed is 70km/h or above, you get an extra fine $2 for every km/habove 70.
• If the driver is drunk, then driver has to pay in addition a driving-under-influence (DUI) penalty of $100 regardless of the speed.
• Otherwise there is no fine for speeding.
The following table show for the inputs speed and for the choice whetherthe driver was drunk the fine the driver has to pay. Please complete the missingfines:
Speed (km/h) Drunk [y/n] Fine45 km/h n $060 km/h n $5075 km/h n $6090 km/h n ?45 km/h y $10060 km/h y ?75 km/h y ?90 km/h y ?
Presentation Exercise 2.4.2 – Present the Fines (5 minutes)One group gets the chance to present the completed table.
Programming Exercise 2.4.3 – Macquarie Island Police II (25 min-utes)Ok, you can use the computer again. In this exercise you will test a programsomeone else has written.
On Moodle you will find a program w3traffic.cpp. It is supposed to com-pute the fine, however it does not compute the right fine.
1. For which of the inputs in above table does it compute the wrong answer.
2. Find the mistake and fix it.
3. Check that the program give the correct answer to all the test cases in thetable above.
12
Do not use any literal number (like 50 or 2) in the in the lines thatyou add or change. Use only constants and variables and arithmeticto compute the fines.
Presentation Exercise 2.4.4 – Present Errors and Fixes (10 minutes)
Two groups get the opportunity to show what the mistakes were, and how theyfixed it. Question to be asked are:
1. Which compiler errors did you get before you fixed it?
2. Was the program correct? If not what was the problem?
3. How did you fix it?
4. Are the fixes elegant and do they adhere to coding style guidelines.
Programming Exercise 2.4.5 – Absolute distance (15 minutes)Write a program that asks for two numbers x and y, which computes z = x− yif x > y and z = y − x otherwise. It should print the value of z to screen.
Peer Exercise 2.4.6 – Help each other (5 minutes)Show the programs ”Absolute distance” and demonstrate it to another group.Explain how far you got. Does the program of the others compile? Does it givethe output you would expect?
Presentation Exercise 2.4.7 – Present ”Absolute distance” (5 min-utes)At least two groups get the chance to show their program for the invitation orthe arithmetic program.
Programming Exercise 2.4.8 – One column of your problem (30 min-utes)Write a program that computes the price or reward for the first column of thetable shown in the description of your problem. The user should be able toselect a product, and the program should return the cost. Do not consider anyspecial options that are mentioned in the description (You’ll have to do that inthe next weeks). Keep in mind to declare and use constants if possible, and notto use magic numbers. Also make sure that all variable names and constantsare relevant to your problem. It should for example not contain a variable fine
from the Macquarie Island Police example. Come up with new names.
13
Presentation Exercise 2.4.9 – Demostrate first protype (10 minutes)
One group get the chance to demonstrate their program to the other studentsand earn 5 marks for it. Questions to be asked are:
1. Does it compile and run?
2. What are the inputs, and what is the output?
3. Does it actually compute the correct answer?
4. Is it a good program?
Programming Exercise 2.4.10 – Your ProblemFor the rest of the lab continue working on your problem, and ask the tutor, oranother student, for help if necessary.
Online Exercise 2.4.11 – Submit a screenshotYour online task of this week is, to run your program (for your problem) andcopy and paste the output into Moodle. In Windows right-click on the menubar, select Edit>Select All, then right-click on the menu bar again and selectEdit>Copy. You can then paste the output into your browser.
14
2.5 Week 5
Programming Exercise 2.5.1 – Macquarie Island Police III (15 min-utes)On Moodle you will find a program w4traffic.cpp. This program computesthe fine for speeding (but not for drinking). The program is correct, in that itcomputes the correct fine for a sober driver. However, the program has verypoor style. It contains
1. Use of magic constants
2. Unused variables
3. Cryptic variable names
4. Poor indentation
5. Poor use of brackets
Identify and correct the problems with the program.
Presentation Exercise 2.5.2 – Macquarie Style issues (5 minutes)One student group get the chance to present the mistakes they found in w4traffic.cpp.Explain what a magic constant, unused variables, cryptic variables names, poorindentation and poor use of brackets you found.
Programming Exercise 2.5.3 – Macquarie Island Police IV (30 min-utes)Macquarie Island Police changed the rules for fining drunk drivers. You shouldchange the calculator to take this into account. The program should ask for thespeed, and whether the driver was drunk. The fines are computed as follows.
• If the driver is not drunk, then driver has to pay
– If the speed is 50km/h or above, a base fine of $50.
– If the speed is 70km/h or above, an extra fine $2 for every km/habove 70.
– If the speed is below 50 km/h, no fine.
• If the driver is drunk, then driver has to pay a driving-under-influence(DUI) penalty of $100 and in addition:
– If the speed is 50km/h or above you will have to pay a base fine of$75.
– If the speed is 60km/h or above you will have to pay an extra fine $3for every km/h above 60.
– If the speed is below 50 km/h nothing except the DUI penalty.
15
• The total fine is the sum of the base fine, the extra fine, plus the DUIpenalty.
You are asked to write a program according to the following pseudo code:
Print a welcome message
Ask for the speed
Ask whether drunk or not
If not drunk
Compute the base fine
Compute the extra fine
else
Compute the base fine
Compute the extra fine
Add the DUI penalty
Display the total fine
When your program runs use the following test cases:
Speed (km/h) Drunk [y/n] Fine45 km/h n $060 km/h n $5075 km/h n $6090 km/h n $9045 km/h y $10060 km/h y $17575 km/h y $22090 km/h y $265
Check that your program satisfies all of these test cases, i.e. check that itcomputes for all inputs the correct fine.
Peer Exercise 2.5.4 – Test fine calculator (10 minutes)In this exercise you are paired with another group. Show them your program,and look at theirs. Does their program compile? Does their program compileall test cases? If it working correct? If the code readable and adhering to codingguidelines?
Presentation Exercise 2.5.5 – Preset test results (10 minutes)Two groups get the chance to present the program of the other group. Discusswhich test cases their program satisfies. Discuss whether it is correct. Discusswhether it is a well designed program.
16
Paper Exercise 2.5.6 – Test cases for your problem (10 minutes)Create a table for your problem, similar to the table given in this section forthe Macquarie Island Police. This table should have one column for each inputor choice that is relevant to compute the cost or reward, and one additionalcolumn for the expected cost or reward. Fill that table with 5 rows, eachspecifying inputs, and what output you expect.
Peer Exercise 2.5.7 – Present your test casesAt least two groups get the opportunity to present their test cases. Use thewhite board to write down which value you will use to test if your program iscorrect.
Online Exercise 2.5.8 – Submit your test casesUpload the test cases that you create onto Moodle. You will be awarded 5 pointfor completing the task.
Programming Exercise 2.5.9 – Your problemUse the remaining time to continue working on your problem. Write a programthat computes the cost or reward for the full table, and take into account thevarious options and exclusions that may exist. If you have questions ask yourtutor. Or ask on Moodle.
Next week you will have to present your program to the tutor for marking.Make sure that your program is well written. The tutor will use the first fourrows of the programming rubric. This means proper structure, proper style,semantics, and correctness will matter. A program that just works will get atmost half of the marks
17
2.6 Week 6
2.6.1 Exercises
Programming Exercise 2.6.1 – Counting letters (20 minutes)This is a first exercise in using loops. Write a program that uses a while loop toread characters, one by one. The loop should stop if the entered character is nota letter; this means it should stop if the character is <’A’ and >’z’. It shouldprint the number of letters entered. Furthermore it should count the number ofcapital letters entered, i.e. letter <’a’, and print the number of capital letters,too.
Hint: You need an if inside of a loop. Ask yourself how many counter youneed.
Presentation Exercise 2.6.2 – The letter counting programm (5 min-utes)One group get the opportunity to present their program. They should answerthe following:
1. What is the pseudo code?
2. What is the best type of loop?
3. When does the loop stop?
4. What counters do you need?
5. What are the conditions that you use?
Programming Exercise 2.6.3 – Your problem (1 hour)This week you will have to complete the first version of the program that solvesyour problem. It should do the following:
• It should print a welcome message.
• It should ask the user to enter the product, the quantity, and which optionsto choose.
• It should compute the cost or reward of that product.
• Print the cost and rewards.
Once you are happy with your do the following:
1. Upload your program on Moodle.
2. Go to see the tutor who will be marking your program. The tutor willuse the last four rows of the programming rubric for marking. It will bemarked out of 10 marks.
View this as an opportunity to get feed back from the tutor on you programs.It will help you to improve the program you have to write for next week.
If you wonder why your program wasn’t marked, then probably because youdid not see the tutor.
18
2.7 Week 7
Programming Exercise 2.7.1 – Your problem (100 minutes)This week you can spend entirely on solving your problem. You should extendthe program you did you last week as follows: It should repeatedly ask the userto enter his choice of product until the user presses ”quit”, it should validatethe input, and it should keep track of the sum of all cost and rewards.
These pseudo code looks as follows:
• It should print a welcome message.
• Repeat the following until the user presses ’Q’.
– It should ask the user to enter the product, the quantity, and whichoptions to choose. It should validate all inputs.
– It should compute the cost or reward of that product.
– Print the cost and rewards.
– It should store the total cost/rewards so far.
It should print the total cost/reward.
Once you are happy with your program do the following:
1. Upload your program on Moodle. The reason for uploading is that thetutor can give you written feedback.
2. Go to see the tutor who will be marking your program. It will be markedout of 10 marks.
View this as an opportunity to get feedback from the tutor on you programs.It will help you to improve your program that you have to submit for theassignment.
19
2.8 Week 8
In the second half of the semester you will be assigned a second problem fromAppendix A. See updated list of assigned lab projects on Moodle. This weekyou are asked to implement it with the knowledge you gained in before the mid-semester break, this means to implement the new project using ifs and loops.In the remaining weeks of the semester you are asked to refactor and extend theprogram, to use functions and arrays where appropriate.
Week 8 will be used to recapitulate the material before the mid-semester.This means you should practice:
• Use of variables and arithmetics.
• Decisions using if and if-else.
• Using loop for input validation.
• Using loops to compute a total.
You will be reassigned a new project. Check for the list that assigns studentsto projects.
Programming Exercise 2.8.1 – New problem (90 minutes)Write, and test a program that does the following: These pseudo code looks asfollows:
• It should print a welcome message.
• Repeat the following until the user presses ’Q’.
– It should ask the user to enter the product, the quantity, and whichoptions to choose. It should validate all inputs.
– It should compute the cost or reward of that product.
– Print the cost and rewards.
– It should store the total cost/rewards so far.
It should print the total cost/reward.
Save this program as you will need it for the next weeks.Note: That this is the same instruction that was given in week 7 for your
old project. Now, with sufficient practice, you should be able to do it withinone lab session.
Presentation Exercise 2.8.2 – Present new progam (10 minutes)Two groups get the chance to present their new program. Discuss if the programsatisfies the requirements. Discuss whether it is correct. Discuss whether it is awell designed program.
Online Exercise 2.8.3 – Self assessmentPlease complete the self-assessment before the start of week 8. You will beawarded 5 points for this exercise.
20
2.9 Week 9
This week you will be using functions and random numbers.Download the file tutor01.cpp from Moodle. It asks the user to give solu-
tions to either linear or quadratic equations.If the user wants to practice linear equations it will ask given numbers a and
b what the solution is of equation
a x + a b = 0
The solution to this equation is −b.If the user wants to practice quadratic equations it will ask given numbers
a and b what the solution is of equation
x2 + (a + b)x + a b = 0
The solutions to this equation are −a and −b. The user has to guess one ofthese.
Programming Exercise 2.9.1 – Random numbersWhen you compile and run the program tutor01.cpp you notice that it alwaysask the same question and the number 0 is always a correct answer. Changethe program as follows:
• The program should instead assign to each variable a and b a randomnumber between −10 and 10 at the beginning of the while-loop (line 46).
• Set the random seed such that it selects different random numbers eachtime you run the program. Set the seed only once in your program.
Compile, run, and test the program.
Paper Exercise 2.9.2 – Understanding functionsThe program tutor01.cpp has two functions readint and signchar. Write foreach function a comment that explains the parameters of the function, what itit computes and returns.
Programming Exercise 2.9.3 – Using FunctionsThe program (including the random numbers) has two problems that occurwhen you are trying solving quadratic equations.
1. The first problem is that the program does not work if you do not enter anumber as answer (What does happen if you enter a letter ’x’?).
2. The other is that it will sometimes print formulas like:
What is a solution to
x^2 + 8 x + -20 = 0
21
The term + -20 is wrong. It should read x^2 + 8 x -20 = 0.
Use the two functions readint and signchar to fix those problem. Note, youdo not have to change those functions. You just have to use them atthe appropriate places in the program.
Programming Exercise 2.9.4 – CountingThe program tutor01.cpp does count the number of successful answer (variablescore), but does not count how many tries have been made. Add a variablesuch that the program counts the number of tries, and prints at the end thescore and the number of tries.
Programming Exercise 2.9.5 – Input validation functionFor each input to your program write a function that can be used to read andvalidate that input. It should check that the values are entered correctly, andif not, ask the user to reenter a value. The function should return a validatedinput value.
Use these function in your program to validate the input.
Presentation Exercise 2.9.6 – Present validation functionTwo groups get the chance to present their validation function. Discuss ifthe program satisfies the requirements. Discuss whether it is correct. Discusswhether it is a well designed program.
Online Exercise 2.9.7 – Define validation function
Select one of the function that you wrote for your program. Go to Moodle,and provide the name, the return type, and a short description of the function.You will be awarded 5 points for this exercise.
22
2.10 Week 10
This weeks lab will continue on the topic of functions. You should know how towrite functions and the difference between reference and value parameters.
Programming Exercise 2.10.1 – Correct mistakesDownload the file tutor02.cpp. It is a flawed and incomplete solution tothe math tutor problem. Your task is to fix it, and to complete it. The filetutor02.cpp contains the functions random pair and check linear.
void random_pair(double first, double second){
first = rand()%(MAXINT-MININT+1) + MININT;
second= rand()%(MAXINT-MININT+1) + MININT;
}
bool check_linear(int guess, int answer){
bool is_equal;
if(guess == answer) {
cout << "Great!\n\n";
is_equal = true;
}
else {
cout << "Oops! The solution was " << answer << ".\n\n";
is_equal = false;
}
}
• The first function random pair should assign to two reference param-eters first and second a random number between MININT and MAXINT.MININT and MAXINT are global constants.
• The second function check linear should return true if the guess isequal to the answer, and it should return false otherwise.
Each of the two functions has one mistake. This means they do currentlynot work correctly. Find the mistakes and correct them. If you find and correctthem the program should work for linear equations.
Programming Exercise 2.10.2 – Extending functionsThe file tutor02.cpp contains an empty function check quadratic. It shouldreturns true if the guess is equal to the answer1 or answer2, and it shouldreturn false otherwise. It should also report success or failure on standardoutput. Please add the code to make this function work.
Paper Exercise 2.10.3 – Divide and ConquerWhen you compute the price or reward for you problem you take a number ofsteps. Your task is to write a function for significant sub-tasks. A sub-task is asmaller task that you program has to take to complete its overall task.
• Identify sub tasks that you have to perform.
23
• Decide for each sub-task what it has to compute (the output) and whatyou need to know to to do the computation (the input).
• Decide on the return type, and decide on the parameters.
• Decide whether the parameters should be value or reference parameters.
• Create a function that performs that task.
• Change your program to use the function.
Presentation Exercise 2.10.4 – Present function for sub-taskTwo groups get the chance to present their function that performs a sub-task.Discuss if the program satisfies the requirements. Discuss whether it is correct.Discuss whether it is a well designed program.
Online Exercise 2.10.5 – Define a sub-task
Pick one of the functions that you wrote for your program this week. Goto Moodle, and provide the name, the return type, the parameters, and a shortdescription of the function. You will be awarded 5 points for this exercise.
24
2.11 Week 11
This weeks lab introduce the topic of arrays. You should know how write to anarray, pass arrays to functions, and the difference between reference and valueparameters.
Programming Exercise 2.11.1 – Complete a function (15 minutes)
Download the file tutor03.cpp. It is a flawed and incomplete solution to themath tutor problem. Your task is to fix it, and to complete it. In the remainderof the lab you have to present your program to the tutor for marking.
The file tutor03.cpp contains a function void random array(int array[],
int size). This function should fill the array array with random values be-tween MININT and MAXINT. Note, that these are global constants.
Use a for-loop to go through the array and assign to each element array[i]a random values between MININT and MAXINT.
Programming Exercise 2.11.2 – Mistakes in functions (20 minutes)
The file tutor03.cpp contains a function void check answer(int guess, int
solutions[], int size, int score). It checks if guess is an element ofarray solutions. If it is it will increment the value of score.
It has two mistakes
• If the user gives a correct answer, it does not increment the value of score.
• If the user gives a wrong answer, it prints some wrong solutions as possibleanswers. It should print the correct solutions.
Identify those two mistakes and fix them. Hint: Both mistakes are insidethe function. Don’t try fixing something outside.
Programming Exercise 2.11.3 – Your lab project (1 hour)This week you will have to complete the program that solves your (second)problem. It should do the following:
• It should print a welcome message.
• Repeat the following until the user presses ’Q’.
– It should ask the user to enter the product, the quantity, and whichoptions to choose. It should validate all inputs.
– It should compute the cost or reward of that product.
– Print the cost and rewards.
– It should store the total cost/rewards so far.
It should print the total cost/reward.
25
In addition is should use functions to validate the inputs, and it should dividethe computation of the cost/reward into sub-taks, and use functions to solvethem. If your solution does not use functions (in a meaningful and correct way)it cannot get full marks.
Upload your program on Moodle, and demonstrate your program to thetutor for marking. You can get at most 10 marks for your program.
26
2.12 Week 12
In the next two weeks you will have to add the use of arrays to your lab project.Make sure that your lab project up to this point uses functions properly, andmake sure that it works. Ask the tutor for help on how to identify sub-tasks,and ask for help on how to define functions. You can also ask that on the forum.
The program you will have to write in the next two weeks should use arraysto keep a record of the last 5 transactions, an allow a user to undo a transaction.On Moodle you will find a program marks.cpp that solves this for a differentproblem, namely for entering marks and computing the average mark. Thisprogram has a number of functions that you can use, or that you should adaptto your use. Program marks.cpp has almost no comments, but is your task tofind out what the different parts are doing.
Paper Exercise 2.12.1 – Using marks.cpp
Compile and run the program. Make yourself familiar with entering marks,displaying marks, and deleting marks. Suggested activities:
• Enter at least half a dozen student marks, and review the marks, delete afew entries, add a few more, and quit.
• Enter just a few marks, and review the marks, try deleting more marksthat you enter and quit.
• Try entering illegal input, and see what happens.
Take this exercise seriously, because you are asked to implement the same func-tionality for your lab project.
Paper Exercise 2.12.2 – ValidationPlease answer the following questions:
• Which functions are used to validate that the user only enters legal input?
• Why does function read num have a while condition involving cin.fail()?What does the while loop do?
• Can you be sure that the return value of read mark is actually a number,and not a string or text? Is this validated? If so, how?
• What does the function next activity ask, and what does it validate?
• Why doesn’t the function read name have to use cin.fail(), i.e. whycan’t the input fail?
Again, if you want to use any of the functions for your own program, or if youwant to adapt them for your purpose, you need to understand how they work.
27
Presentation Exercise 2.12.3 – Answers on validation functionsOne group gets the chance to answer the questions on the validation functions.
Paper Exercise 2.12.4 – Array updatesPlease answer the following?
• What will the function print stores print? Why is the return type void?Will it change the parameters that are arrays?
• What will the function add mark and add name do? What are the param-eters used for? Which parameters are reference parameters? Which ofthem will be changed? Is it guaranteed that the function will not violatethe array bounds? What does it do to guarantee it? What would happenif the for-loop would start for(int i = 0; i<STORESIZE; i++)?
• When the program ”deletes” an item it only decrements marks in store--;
and names in store--;. Why does it not need to change mark store andname store?
• What is this line
if(num students>0 && marks in store>0 && names in store>0)
all about? Why do you need this to be true, before you delete an entry?
• What are these lines
num students--;
total = total - mark store[marks in store-1];
all about? Why do you need them to ensure that the average is correct?
Presentation Exercise 2.12.5 – Answers on array updatesOne group gets the chance to answer the questions on the validation functions.
There are no programming exercises this week. Just make sure you under-stand the example program such that you can apply the same techniques toyour own program.
Programming Exercise 2.12.6 – Your problemExtend you program as follows:
• It should ask the user (1) whether they want to order one more item (orcompute one more energy cost/reward), (2) whether they want to see thelast 5 items, (3) whether they want to delete the last, (4) whether wantto see the current total, or (5) want to quit.
28
• It should compute the cost or reward (This is what your program shoulddo already.)
• It should store up to 5 entries. The example program mark.cpp storesthe name and the mark. Decide which information you want to store witheach entry for your program.
• It should show, if requested, the last five entries (or all entries, if less thanfive have been entered so far).
• It should show, if requested, the total of all costs/rewards so far entered.
• It should delete, if requested, the last entry (if it exists).
• It should show the total of all costs and reward and quit, if the userrequests to quit.
Online Exercise 2.12.7 – Define data to store in arraysSubmit on Moodle which information you want to store for users to review. Theprogram mark.cpp, for example, stores the student name and the mark.
29
2.13 Week 13
This week there will be a short exercise on pointers. The rest of the time canbe used to finish you lab project and to have it marked.
Programming Exercise 2.13.1 – Pointers (20 minutes)This first exercise lets you explore how one pointer can be used to point todifferent variables, and thus to different memory locations. The program is asimple program that as the user to enter letters, and the program will count howmany of these letters are upper or lower case letter. On Moodle you will finda file week13 1.cpp. Your task is to add a few lines to complete the program.However, there are a few constraints:
• Don’t modify anything above the comment: //Don’t change anything
above this line
• Don’t modify anything below the comment: //Don’t change anything
below this line
• You should not introduce new variables, nor use arithmetic, nor incrementoperators.
• The variables capital and lower can only appear on the right hand side ofan assignment.
• Use pointers.
The output should look like this:
Please enter letters. Any other key to stop. HelloWorld!
The number of lower case letters was 8
The number of capital letters was 2
Presentation Exercise 2.13.2 – Present pointer programTwo groups get the chance to present their changes to the function that usespointers. Discuss the changes mae to the program. Discuss how the programkeeps track of the counters.
Programming Exercise 2.13.3 – Arrays and Pointers (20 minutes)
On Moodle you can find a file week13 2.cpp. Compile it and run it. Can youexplain the output?
The file week13 2.cpp has a function print array. Change the function andreplace the array by a pointer. Your solution should use operations on pointersrather than array operations. This means that in you code you should not usesquare brackets [] to indicate that a parameter is an array (the parameter willbe a pointer) nor should you use the notation [i] to access the element inposition i.
30
Presentation Exercise 2.13.4 – Present array and pointer programTwo groups get the chance to present their changes to the function that usesarrays and pointers. Discuss the changes made to the program.
Programming Exercise 2.13.5 – Your problemContinue working on the programming task of last week, and show you programto the tutor for marking. See last weeks lab description for what is expectedfrom your program.
Upload your program and show it to the tutor for marking.
2.14 Week 14
Time to complete your lab project, to show it to your tutor for marking, andto ask questions.
Online Exercise 2.14.1 – Self-assessmentComplete the self assessment on Moodle.
31
A Programming Projects
A.1 Car rental 1
This program is for a car rental agency. Your program will have to compute thetotal cost of a rental. This agency has three types of cars, and the rates per dayare as follows: Drivers age 25 or younger will have to pay a surcharge of 20 %.
Renting for lessthan 7 days
Renting for 7days or more.
Compact car $50 $45Mid-size car $70 $60Luxury car $100 $75
Table 2: Price list for problem A.1
A.2 Car rental 2
This program is for a car rental agency. Your program will have to compute thetotal cost of a rental. This agency has two types of cars, and the rates per dayare as follows: All cars come with a basic insurance that covers damage to third
Renting for lessthan 7 days
Renting for 7days or more.
Compact car $50 $48Mid-size car $60 $55
Table 3: Price list for problem A.2
parties. Comprehensive insurance cover costs $30 for compact cars and $40 formid-size cars.
A.3 Car rental 3
This program is for a car rental agency. Your program will have to compute thetotal cost of a rental. This agency has two types of cars, and the rates per dayare as follows: All cars come with a basic insurance that covers damage to third
Driver above 25years of age
Driver 25 yearsold or younger.
Compact car $60 $80Mid-size car $75 $100
Table 4: Price list for problem A.3
parties. Comprehensive insurance cover costs $30 for compact cars and $40 formid-size cars.
32
A.4 Car rental 4
This program is for a car rental agency. Your program will have to computethe total cost of a rental. This agency has three types of cars, and the rates perday are as follows: You can order an child seat for $50 per rental, and a GPS
Renting for lessthan 7 days
Renting for 7days or more.
Compact car $40 $55Mid-size car $55 $50Luxury car $70 $60
Table 5: Price list for problem A.4
navigations system for $6 per day.
A.5 Car rental 5
This program is for a car rental agency. Your program will have to compute thetotal cost of a rental. This agency has four types of cars, and the rates per dayare as follows: You can order an child seat for $40 per rental. Drivers age 25 or
Compact car $40Mid-size car $55Luxury car $70SUV $ 60
Table 6: Price list for problem A.5
younger will have to pay a surcharge of 20 % on the daily rates.
A.6 Car rental 6
This program is for a car rental agency. Your program will have to computethe total cost of a rental. This agency has four types of cars, and the rates perday for rental up to 7 days are as follows: If the rental is 7 days or longer, the
Compact car $40Mid-size car $55Luxury car $70SUV $60
Table 7: Price list for problem A.6
rates are 10% lower. All car come with a basic insurance that covers damageto third parties. Comprehensive insurance cover costs $40 per day, regardlessof the length of the rental.
33
A.7 Car rental 7
This program is for a car rental agency. Your program will have to computethe total cost of a rental. This agency has three types of cars, and the rates perday are as follows: Renting from an airport location cost $10 extra per rental.
Renting for lessthan 7 days
Renting for 7days or moreand less than28.
Renting for 28days or more.
Compact car $60 $55 $50Mid-size car $80 $70 $60Luxury car $100 $85 $70
Table 8: Price list for problem A.7
A.8 Car rental 8
This program is for a car rental agency. Your program will have to computethe total cost of a rental. This agency has two types of cars, and the rates perday are as follows: Drivers age 25 or younger will have to pay a surcharge of
Compact car $50Mid-size car $60
Table 9: Price list for problem A.8
10 % on the daily rates. You can order an child seat for $60 per rental, and aGPS navigations system for $5 per day. All cars come with a basic insurancethat covers damage to third parties. Comprehensive insurance cover costs $40for compact cars and $50 for mid-size cars.
A.9 Car rental 9
This program is for a car rental agency. Your program will have to compute thetotal cost of a rental. This agency has two types of cars, and the rates per dayare as follows: Drivers age 25 or younger will have to pay a surcharge of 10 %
Renting for lessthan 7 days
Renting for 7days or moreand less than28.
Renting for 28days or more.
Compact car $55 $50 $45Mid-size car $70 $60 $55
Table 10: Price list for problem A.9
34
on the daily rates. You can order an child seat for $60 per rental.
A.10 Car rental 10
This program is for a car rental agency. Your program will have to compute thetotal cost of a rental. This agency has three types of cars, and the rates per dayare as follows: Renting from an airport location cost $10 extra per rental. You
Renting for lessthan 7 days
Renting for 7days or more.
Compact car $50 $49Mid-size car $55 $50Luxury car $65 $60
Table 11: Price list for problem A.10
can order an child seat for $7 per day, or for$60 per rental, whatever is less.
A.11 Coffee shop 1
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Take away cost 10 cents extra per drink. All coffee
Regular Large.Long black $3.50 $3.80Flat white $3.90 $4.20Cappuccino $4.00 $4.30Tea $3.00 $3.10
Table 12: Price list for problem A.11
products can also be made decaf, which will cost 20 cents extra.
A.12 Coffee shop 2
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Specialty teas will cost 10 cent extra.
Regular Large Extra large.Long black $3.50 $3.80 $4.00Flat white $3.90 $4.20 $4.50Cappuccino $4.00 $4.30 $4.60Tea $3.00 $3.10 $3.20
Table 13: Price list for problem A.12
35
A.13 Coffee shop 3
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Flat whites and cappuccinos can also be made
Regular LargeLong black $2.50 $2.80Flat white $2.90 $3.20Cappuccino $3.00 $3.30Tea $2.00 $2.10
Table 14: Price list for problem A.13
with soy milk, which will cost 30 cent extra.
A.14 Coffee shop 4
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Milkshakes only come in the sizes large and extra
Regular Large. Extra LargeLong black $2.50 $2.80 $3.00Flat white $2.90 $3.20 $3.50Tea $2.00 $2.10 $2.20Milkshake - $3.50 $4.50
Table 15: Price list for problem A.14
large.
A.15 Coffee shop 5
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Long blacks and flat whites do not come as extra
Small Regular Large Extralarge.
Long black $3.50 $3.80 $4.00 -Flat white $3.90 $4.20 $4.50 -Cappuccino $4.00 $4.30 $4.60 $4.80Tea $3.00 $3.10 $3.20 $3.50
Table 16: Price list for problem A.15
large.
36
A.16 Coffee shop 6
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer:
Regular LargeLong black $3.00 $3.30Flat white $3.40 $3.70Cappuccino $3.50 $3.80Mocha $3.60 $4.00Latte $3.30 $3.50Tea $3.00 $3.10
Table 17: Price list for problem A.16
A.17 Coffee shop 7
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: If you order 3 drinks of the same type and size
Regular LargeLong black $2.60 $2.70Flat white $2.80 $3.10Cappuccino $3.10 $3.30Tea $2.10 $2.50
Table 18: Price list for problem A.17
you get the fourth drink free.
A.18 Coffee shop 8
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Tea and long blacks can also be ordered iced. This
Small Regular Large Extralarge.
Long black $3.50 $3.70 $4.00 $4.30Flat white $3.80 $4.20 $4.50 $4.80Cappuccino $4.00 $4.30 $4.60 $5.00Tea $3.00 $3.10 $3.30 $3.50
Table 19: Price list for problem A.18
will cost 50ct extra.
37
A.19 Coffee shop 9
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: During happy hour from 5pm to 6pm, all large
Regular Large. Extra LargeLong black $3.50 $3.80 $4.00Flat white $3.90 $4.20 $4.50Tea $3.00 $3.10 $3.20
Table 20: Price list for problem A.19
drinks are on sale for the price of a regular drink, and all extra large drink forthe price of a large drink.
A.20 Coffee shop 10
This program is for a coffee shop. It should compute the price of an order. Thefollowing drinks are on offer: Only regular size is available for take-away.
Regular LargeLong black $2.80 $3.00Flat white $2.90 $3.20Cappuccino $3.00 $3.30Tea $2.00 $2.10
Table 21: Price list for problem A.20
A.21 Sandwich Shop 1
This program is for a sandwich shop. It computes the price of a sandwich. A
White RyeCheese $2.80 $3.00Egg $2.90 $3.20Ham $3.00 $3.30Ham and cheese $2.00 $2.10
Table 22: Price list for problem A.21
toasted sandwich cost 50 ct extra, however, an egg sandwich cannot be toasted.
A.22 Sandwich Shop 2
This program is for a sandwich shop. It computes the price of a sandwich. If asandwich is ordered for take away it will cost 20 ct less.
38
Plain Rye RollCheese $2.50 $2.80 $3.00Egg $2.80 $3.00 $3.20Ham $2.80 $3.00 $3.20Ham and cheese $3.00 $3.20 $3.50
Table 23: Price list for problem A.22
A.23 Sandwich Shop 3
This program is for a sandwich shop. It computes the price of a sandwich.All sandwiches except the cheese and the egg sandwich can be ordered with
Plain RollCheese $2.80 $3.00Egg $2.90 $3.20Ham $3.00 $3.30Corned beef $3.00 $3.30Chicken $3.20 $3.50
Table 24: Price list for problem A.23
additional cheese. This will cost 60 cent extra.
A.24 Sandwich Shop 4
This program is for a sandwich shop. It computes the price of a sandwich. All
Plain RyeCheese $2.50 $3.00Egg $2.70 $3.20Ham $3.00 $3.50Corned beef $3.00 $3.50Chicken $3.20 $3.70
Table 25: Price list for problem A.24
rye sandwiches will come with a free pickle. If a customer want a pickle with aplain sandwich it will cost 20 cent extra.
A.25 Sandwich Shop 5
This program is for a sandwich shop. It computes the price of a sandwich. Thecustomer can choose as condiments tomato sauce, mustard, mayo, and pickle.Two condiments are free, every additional condiment will cost 20 ct extra.
39
White RyeCheese $2.80 $3.30Ham $2.90 $3.40Chicken $3.00 $3.50Beef $3.00 $3.50
Table 26: Price list for problem A.25
A.26 Sandwich Shop 6
This program is for a sandwich shop. It computes the price of a sandwich.Cheese can be added to all sandwiches for 50 cent. Plain sandwiches can be
Plain RollHam $2.70 $3.20Beef $2.80 $3.30Chicken $3.00 $3.40Lamb $3.00 $3.40
Table 27: Price list for problem A.26
toasted, for an additional 10 cent.
A.27 Sandwich Shop 7
This program is for a sandwich shop. It computes the price of a sandwich. All
White Sourdough RollCheese $2.50 $3.00 $3.50Egg $2.70 $3.20 $3.70Ham $3.00 $3.50 $3.90
Table 28: Price list for problem A.27
sandwiches can be toasted, except if they are egss sandwiches or rolls. Toastingwill cost 50 cent extra.
40
A.28 Sandwich Shop 8
This program is for a sandwich shop. It computes the price of a sandwich.There is a special deal of any plain sandwich order with a coffee or tea for $3.00.Otherwise coffee or tea is $1.50.
Plain Rye RollCheese $1.80 $2.00 $3.00Egg $1.50 $1.80 $2.80Ham $1.80 $2.00 $3.00Ham and cheese $2.00 $2.20 $3.20
Table 29: Price list for problem A.28
A.29 Sandwich Shop 9
This program is for a sandwich shop. It computes the price of a sandwich.Cheese can be added to all sandwiches, exept for the cheese sandwich, for anadditional 30 cent. Plain sandwiches can be toasted for $0.20.
Plain RollCheese $2.80 $3.20Ham $2.80 $3.20Chicken $3.20 $3.70
Table 30: Price list for problem A.29
A.30 Sandwich Shop 10
This program is for a sandwich shop. It computes the price of a sandwich. All
Plain RollCheese $2.50 $3.00Ham $3.00 $3.50Corned beef $3.00 $3.50Chicken $3.20 $3.70
Table 31: Price list for problem A.30
sandwiches can be ordered with additional cheese. This costs $0.20 for plainsandwiches, and $0.30 for rolls.
41
A.31 Cinema 1
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Glasses for 3D movies cost $3.00.
Normal PremiumShouf Shouf Habibi $5.00 $7.00The Interview (3D) $7.00 $9.50New Kids Turbo (3D) $7.00 -Black Butterflies $5.00 -
Table 32: Price list for problem A.31
A.32 Cinema 2
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Glasses for 3D movies cost $2.00, but are included for
Normal PremiumShouf Shouf Habibi $7.00 $10.00The Interview (3D) $10.00 $16.50New Kids Turbo (3D) $10.00 $16.50Black Butterflies $7.00 $10.00
Table 33: Price list for problem A.32
free with a premium ticket.
A.33 Cinema 3
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. 3 D movies are not offered at Super Tuesday prices.
Normal Premium Super TuesdayShouf Shouf Habibi $7.00 $10.00 $5.00The Interview (3D) $10.00 $16.50 -New Kids Turbo (3D) $10.00 $16.50 -Black Butterflies $7.00 $10.00 $5.00
Table 34: Price list for problem A.33
A.34 Cinema 4
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Tickets for children that are accompanied by two adults,are half of the normal child ticket.
42
Adult ChildShouf Shouf Habibi $8.00 $5.00The Interview (3D) $10.00 $6.00New Kids Turbo (3D) $10.00 $6.00Black Butterflies $8.00 $5.00
Table 35: Price list for problem A.34
A.35 Cinema 5
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. It has a ”get three - pay two” deal. Three tickets - for
Regular PremiumShouf Shouf Habibi $8.00 $10.00The Interview (3D) $10.00 $15.00New Kids Turbo (3D) $10.00 $15.00Black Butterflies $8.00 $10.00
Table 36: Price list for problem A.35
the same movie and seating - cost the price of two tickets. ”Get three- pay two”does not apply to 3D movies.
A.36 Cinema 6
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. The price for a group is per person.
Regular Premium SuperTuesday
Groups(more than5 people)
Shouf Shouf Habibi $8.00 $12.00 $6.00 $7.00The Interview (3D) $10.00 $18.00 $8.00 $8.00New Kids Turbo (3D) $10.00 $18.00 $8.00 $8.00Black Butterflies $8.00 12.00 $6.00 $7.00
Table 37: Price list for problem A.36
A.37 Cinema 7
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Movie club members get $2.00 off for all normal movies,and $3.00 off for all 3D movies.
43
Regular PremiumShouf Shouf Habibi $5.00 $7.00Polish Bride (3D) $9.00 $12.50New Kids Turbo (3D) $9.00 $12.50Black Butterflies $5.00 $7.00
Table 38: Price list for problem A.37
A.38 Cinema 8
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Free large size popcorn for all 3D movies, otherwise it
Regular PremiumShouf Shouf Habibi $6.00 $10.00The Interview (3D) $12.00 $18.00New Kids Turbo (3D) $12.00 $18.00Black Butterflies $8.00 $10.00
Table 39: Price list for problem A.38
will cost $2.00 for a normal size, and $3.00 for a large size bucket of popcorn.
A.39 Cinema 9
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Adults that accompany children for Miffy will only pay
Adult ChildShouf Shouf Habibi $8.00 $8.00Miffy $8.00 $6.00Black Book (3D) $10.00 -New Kids Turbo (3D) $10.00 $8.00
Table 40: Price list for problem A.39
the price of a child ticket. Black Book is not suitable for children.
A.40 Cinema 10
This program is for a cinema. It computes the price of a movie ticket. It offersdifferent types of seats. Movie club members get 25 % off on all Regular andPremium Tickets.
44
Regular Premium Super TuesdayShouf Shouf Habibi $8.00 $12.00 $5.00The Interview (3D) $12.00 $20.00 $8.00New Kids Turbo (3D) $12.00 $20.00 $8.00Black Butterflies $8.00 $12.00 $5.00
Table 41: Price list for problem A.40
A.41 Renewable Energy 1
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity.
The following table shows the cost or reward. The program needs to computethe cost or earnings.
Reward perkWh produced
Cost per kWhconsumed
Monday to Friday 7am to 7pm $0.15 $0.12Monday to Friday 12am to 7am $0.00 $0.07Monday to Friday 7pm to 12am $0.00 $0.09Saturdays $0.12 $0.10Sunday $0.12 $0.08
Table 42: Price list for problem A.41
A.42 Renewable Energy 2
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity. The following tableshows the cost or reward. The government will also pay an additional 3 centsubsidy for any kWh produced during the week by biomass.
Reward perkWh produced
Cost per kWhconsumed
Monday to Friday $0.15 $0.12Saturdays $0.12 $0.10Sunday $0.12 $0.08
Table 43: Price list for problem A.42
45
A.43 Renewable Energy 3
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity. The following tableshows the cost or reward. The government will also pay an additional 4 cent
Reward perkWh produced
Cost per kWhconsumed
Weekday 6am to 8pm $0.15 $0.12Weekday 8pm to 6am $0.05 $0.07Weekend 6am to 8pm $0.12 $0.10Weekend 8pm to 6am $0.06 $0.08
Table 44: Price list for problem A.43
subsidy for any kWh produced during the week by solar. Of course solar powercannot be produced from 8pm to 6am.
A.44 Renewable Energy 4
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity. The following tableshows the cost or reward. The government will pay an additional 5 cent subsidy
Reward perkWh produced
Cost per kWhconsumed
Weekday 6am to 8pm $0.15 $0.12Weekday 8pm to 6am $0.05 $0.07Weekend 6am to 8pm $0.12 $0.10Weekend 8pm to 6am $0.12 $0.08
Table 45: Price list for problem A.44
for any kWh produced during the day by solar or wind.
A.45 Renewable Energy 5
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in any
46
period a farmer may both consume and produce electricity. The following tableshows the cost or reward. The farmer get $10 premium, if he produces more
Reward perkWh produced
Cost per kWhconsumed
Monday to Friday 7am to 7pm $0.15 $0.12Monday to Friday 7pm to 7am $0.08 $0.08Weekend 7am to 7pm $0.12 $0.10Weekend 7pm to 7am $0.10 $0.08
Table 46: Price list for problem A.45
than 100 kWh on a weekday from 7am to 7pm.
A.46 Renewable Energy 6
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity. The following tableshows the cost or reward. A farmer get the electricity for free, if he produces in
Reward perkWh produced
Cost per kWhconsumed
Weekday 6am to 8pm $0.10 $0.12Weekday 8pm to 6am $0.05 $0.07Weekend 6am to 8pm $0.08 $0.10Weekend 8pm to 6am $0.06 $0.08
Table 47: Price list for problem A.46
a given period more electricity than he uses.
A.47 Renewable Energy 7
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity. The following tableshows the cost or reward. If the farmer produces more than 100 kWh duringthe day, he will not get any reward for the electricity produced in excess of 100kWh.
47
Reward perkWh produced
Cost per kWhconsumed
Weekday 6am to 8pm $0.15 $0.12Weekday 8pm to 6am $0.08 $0.07Weekend 6am to 8pm $0.12 $0.10Weekend 8pm to 6am $0.10 $0.08
Table 48: Price list for problem A.47
A.48 Renewable Energy 8
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity.The following tableshows the cost or reward. The farmer will get $5.00 poor weather compensation
Reward perkWh produced
Cost per kWhconsumed
Monday to Friday $0.25 $0.20Saturdays $0.20 $0.15Sunday $0.15 $0.12
Table 49: Price list for problem A.48
for any day during which he cannot produce any energy by wind or solar.
A.49 Renewable Energy 9
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he willbe charged. The prices depend on time of day and week day. Note that inany period a farmer may both consume and produce electricity. The followingtable shows the cost or reward. The farmer gets a rebate of 25% on any kWh
Reward perkWh produced
Cost per kWhconsumed
Weekday 6am to 8pm $0.10 $0.12Weekday 8pm to 6am $0.06 $0.08Weekend 6am to 8pm $0.08 $0.10Weekend 8pm to 6am $0.06 $0.08
Table 50: Price list for problem A.49
consumed above 100kWh within a given period.
48
A.50 Renewable Energy 10
This program computes the cost or earnings for a farmer who feeds electricityfrom renewable (solar, wind, biomass) into the net. If the farmer feeds excessenergy into the FEA net he will be rewarded, if he needs electricity he will becharged. The prices depend on time of day and week day. Note that in anyperiod a farmer may both consume and produce electricity. The following tableshows the cost or reward. The farmer will get regardless of the day $0.20 for
Reward perkWh produced
Cost per kWhconsumed
Monday $0.16 $0.20Tuesday to Friday $0.18 $0.20Saturdays $0.16 $0.18Sunday $0.12 $0.16
Table 51: Price list for problem A.50
the first 50 kWh produced on any day.
49
B Programming RubricExceptional
Accepta
ble
Am
ate
ur
Unsa
tisfacto
ry
Str
uct
ure
Th
est
ruct
ure
of
the
pro
-gra
mre
flec
tsa
dec
om
po-
siti
on
of
the
pro
ble
min
tosm
aller
pro
ble
ms.
Th
ed
iffer
ent
com
pon
ents
are
kep
t,if
poss
ible
,gen
eral
an
den
ab
lere
use
ina
dif
-fe
rent
conte
xt.
Th
est
ruct
ure
of
the
pro
gra
mre
flec
tsa
de-
com
posi
tion
of
the
pro
ble
min
tom
ost
im-
port
ant
sub
-pro
ble
ms.
Th
ed
iffer
ent
com
po-
nen
tsso
lve
sub
task
su
sin
ggen
eric
ap
pro
ach
es,
even
ifth
eim
ple
men
-ta
tion
makes
reu
sein
ad
iffer
ent
conte
xt
un
likel
y.
Th
ep
rogra
mre
flec
tsd
ecom
posi
tion
into
sub
-pro
ble
ms
that
have
un
clea
rb
ou
nd
ari
esor
over
lap
.T
he
imp
le-
men
tati
on
issp
ecifi
cto
the
pro
ble
mat
han
d,
an
dre
use
ina
diff
eren
tco
nte
xt
isex
trem
ely
un
likel
y.
Th
ep
rogra
mh
as
ei-
ther
no
dis
cern
ible
stru
c-tu
re,
or
itre
flec
tsad
-h
oc
dec
om
posi
tion
for
the
sake
of
dec
om
posi
-ti
on
.T
he
pro
gra
mex
-h
ibit
sca
rgo
cult
pro
-gra
mm
ing.
Th
eco
de
ap
-p
ears
tob
ep
atc
hed
to-
get
her
.
Pro
gra
mm
ing
style
Th
eco
de
use
sla
you
tto
convey
the
stru
ctu
reof
the
pro
gra
mcl
earl
y.D
iffer
ent
com
pon
ents
are
easi
lyre
cogn
ized
.N
am
esare
by
them
selv
esm
ean
-in
gfu
lif
they
refe
rto
the
spec
ific
pro
ble
man
dgen
eric
ifth
eyre
fer
top
art
of
the
cod
eth
at
isre
usa
ble
.T
he
cod
ead
-h
eres
toa
giv
enco
din
ggu
idel
ine.
All
ou
tpu
tis
spel
led
corr
ectl
y,w
ith
ap
rop
erla
you
t.
Th
ela
you
tof
the
pro
-gra
mm
akes
itp
oss
ible
toid
enti
fyth
est
ruct
ure
of
the
pro
gra
m.
Nam
esare
mea
nin
gfu
lin
the
conte
xt
of
the
pro
ble
m.
Th
eco
de
ad
her
esto
gen
eral
good
cod
ing
pra
ctic
es,
an
dth
eou
tpu
tis
spel
led
cor-
rect
lyw
ith
on
lym
inor
glitc
hes
inla
you
t.
Th
ela
you
tof
the
pro
-gra
mm
akes
itp
oss
ible
toid
enti
fyth
est
ruct
ure
of
the
pro
gra
mw
ith
som
eeff
ort
.N
am
esm
ake
sen
seto
ap
erso
nfa
milia
rw
ith
the
pro
ble
m.
Th
eco
de
makes
ad
her
esto
som
egood
pra
ctic
es,
bu
tig
-n
ore
soth
ers.
Som
em
inor
spel
lin
gm
ista
kes
,or
mis
-ta
kes
inla
you
t.
Th
ela
you
tof
the
pro
-gra
mis
coin
cid
enta
l,an
dm
akes
itd
ifficu
ltto
iden
-ti
fyth
est
ruct
ure
of
the
pro
gra
m.
Nam
esare
cryp
tic.
No
dis
cern
ible
effort
was
mad
eto
ad
her
eto
com
mon
cod
ing
pra
c-ti
ces.
Th
eoutp
ut
con
-ta
ins
spel
lin
gm
ista
kes
,an
dd
oes
not
make
an
ef-
fort
toen
sure
pro
per
for-
matt
ing.
50
Exceptional
Accepta
ble
Am
ate
ur
Unsa
tisfacto
ry
Sem
an
tics
Th
ep
rogra
mu
ses
the
pro
gra
mm
ing
con
stru
ctco
rrec
tly
an
dco
mp
e-te
ntl
y.T
he
pro
gra
md
oes
avoid
pro
gra
m-
min
gsh
ort
cuts
,an
dd
oes
not
ab
use
synta
x.
Th
ere
are
no
sup
erfl
uou
sst
ate
men
tsor
con
di-
tion
s,n
od
ead
cod
e,n
ou
nu
sed
vari
ab
les,
no
un
init
ialize
dvari
ab
les,
no
pote
nti
al
div
isio
nby
zero
,arr
ay
bou
nd
svio
lati
on
,m
emory
leaks,
or
oth
erru
n-t
ime
erro
rs.
Th
ep
rogra
mu
ses
most
con
stru
cts
corr
ectl
yan
das
inte
nd
ed,
an
dis
on
lyso
met
imes
over
lyco
mp
li-
cate
d.
Itm
ay
conta
ina
few
min
or
sem
anti
cer
-ro
rs,
such
as
dea
dco
de,
or
unu
sed
vari
ab
les,
bu
tn
oth
ing
that
wou
ldca
use
aru
n-t
ime
erro
r.
Th
ep
rogra
mw
ork
sm
ost
of
the
tim
esco
rrec
tly
giv
enso
me
imp
lici
tas-
sum
pti
on
sab
ou
tit
su
se.
Th
ep
rogra
mu
ses
con
-st
ruct
sd
iffer
entl
yfr
om
thei
rin
ten
ded
use
.T
her
em
ay
be
afe
wru
nti
me
er-
rors
that
man
ifes
tth
em-
selv
esfo
ru
nu
sual
inp
ut
or
for
cert
ain
com
piler
s.
Th
ep
rogra
mh
as
sev-
eral
min
or
run
tim
eer
-ro
rs,
like
use
of
init
ial-
ized
vari
ab
les,
or
on
eor
more
fata
lru
nti
me
er-
rors
.It
use
sp
rogra
m-
min
gco
nst
ruct
sw
ith
no
regard
for
thei
rse
manti
csn
or
inte
nd
edu
se.
Fu
nct
ion
al
cor-
rect
nes
s.T
he
pro
gra
msa
tisfi
esall
requ
irem
ents
an
dp
ro-
du
ces
the
corr
ect
beh
av-
ior
for
all
poss
ible
legal
inp
ut.
Ith
an
dle
sin
cor-
rect
inp
ut
an
dre
spon
ds
ad
equ
ate
ly.
Th
ep
rogra
msa
tisfi
esth
ere
qu
irem
ents
alm
ost
com
ple
tely
,an
dp
rod
uce
sth
eco
rrec
tan
swer
for
all
obvio
us
legal
inp
ut.
Ith
an
dle
sall
inco
rrec
tin
pu
tw
ith
ou
tfa
tal
failu
res.
Th
ep
rogra
msa
tisfi
esth
eco
rere
qu
irem
ents
.S
om
ere
qu
irem
ents
mig
ht
not
be
ad
dre
ssed
.It
pro
-d
uce
sth
eco
rrec
tou
tpu
tfo
robvio
us
legal
inp
ut.
Th
ep
rogra
md
oes
not
sati
sfy
core
requ
irem
ents
.It
isea
syto
fin
dex
am
ple
wh
ere
the
pro
gra
mco
m-
pu
tes
the
wro
ng
resu
lt.
Th
ep
rogra
md
oes
fail
for
un
exp
ecte
din
pu
t.
51
Exceptional
Accepta
ble
Am
ate
ur
Unsa
tisfacto
ry
Effi
cien
cyT
he
solu
tion
use
sta
ilore
dalg
ori
thm
sin
an
effici
ent
way,
or
ap
plies
exis
tin
gso
luti
on
sin
asm
art
way
toim
pro
ve
effici
ency
.
Th
eso
luti
on
use
sco
m-
mon
data
stru
ctu
res
an
dalg
ori
thm
sto
ensu
reeffi
-ci
ency
.
Aso
luti
on
that
isth
ere
-su
ltfr
om
ast
raig
htf
or-
ward
bu
tin
effici
ent
ap
-p
roach
toth
ep
rob
lem
.
An
over
lyco
mp
lica
ted
an
din
effici
ent
att
emp
tto
solv
eth
ep
rob
lem
.
Doc
um
enta
tio
nT
he
cod
eis
wel
ld
oc-
um
ente
d.
Com
men
td
escr
ibes
the
main
com
pon
ents
,vari
able
s,fu
nct
ion
s.C
om
men
tsare
use
dto
des
crib
eth
est
ruct
ure
.T
he
com
men
tsare
up
tod
ate
.T
he
com
-m
ents
are
rele
vant,
an
dm
ake
sen
seto
som
eon
eu
nfa
milia
rw
ith
the
cod
e.
Com
men
tsd
escr
ibe
most
com
pon
ents
,vari
ab
les
an
dfu
nct
ion
s.S
om
eco
mm
ents
mig
ht
be
date
d;
most
com
men
tm
ay
make
sen
seto
som
eon
eu
nfa
mil
iar
wit
hco
de.
Th
ere
isvis
ible
att
emp
tto
com
men
tall
com
-p
on
ents
an
dfu
nct
ion
s.H
ow
ever
,so
me
com
men
tsm
ight
be
ou
tdate
d,
or
on
lyre
levant
toso
meo
ne
fam
ilia
rw
ith
the
cod
e.
Th
ere
are
no
com
men
ts,
or
poor
com
men
t;ou
t-d
ate
d,ir
rele
vant,
or
cryp
-ti
c.
52