Professional Documents
Culture Documents
Session 2 Student Instructions PDF
Session 2 Student Instructions PDF
Starting Up
1. Create a local subfolder ie NOT in your shared drive, but on the desktop
(Remember at the end to save the .cpp files back either to the dropbox on NOW
or save the whole project to your drive).
SYNTAX (as covered in lecture) if/else example:
if (x==1)
{
cout<<x is 1!<<endl;
}
else
{
cout<<x is not 1<<endl;
}
Exercise 1
Download Session2.zip from NOW and unzip it into your folder
Double click the .sln (Visual Studio solution) file which will start up Visual Studio.
Note that the program contains 2 variables, an INTEGER called aInt, and a FLOATING
POINT number called bFloat.
They have been initialised to particular values: 5 and 3.6.
Note the SEMICOLON at the end of the declaration.
Part A
ADD SOME CODE (after the declarations) that does the following:
It uses the if syntax as shown to output the words Too low if aInt is below 10, and
Too High otherwise.
VERIFY that the program compiles and builds and, when ctrl-F5 is entered, displays
Too low.
Change the value of aInt to 200 by an ASSIGNMENT statement just before the if.
(Remember to put a semicolon at the end.)
TEST to verify that the changed program now display Too High when run.
Look up the use of else if to allow more choices. (Google is your friend)
Change the code to use else if so that it displays Too Low if aInt is below 10, Perfect if
aInt is EQUAL to 10, and Too High otherwise. (Recall from the lecture how we test for
equality.)
TEST by changing the assignment statement to ensure that Perfect will be displayed if
aInt is 10.
Part B
Use Edit|Advanced|Comment Selection (or the ctrl shortcuts) to comment out all the code
you have just added.
Now we will add a new section to check that it also works when applied to a floating point
variable ie bFloat.
What do you think will happen if you add the following code?
if (bFloat==3.6)
{
cout<<" Hooray 3.6 found"<<endl;
}
This shows that your program is at this point, waiting to execute the line.
Look at the bottom left window. Should show current values of variable ie bFloat.
9. Does it have the value you expect? Is it a value of 3.6 or something else?
10. Hover mouse above the variable name anywhere in your program.
It will show you current value ie the values they have just before executing the line where
the breakpoint is. (So if the line is an assignment, the breakpoint occurs BEFORE the
value has changed.)
Get program to step to the next line:
12. Select Debug|Stepover.
13. Does the yellow marker get to the Hooray line?
Using the debugger like this will allow you to see the decisions made by your code as a
result of the tests (if statements) you have set up. Sometimes this can be quite a surprise!
If it doesn't do the things you expect, stop debugging, and start again, setting up multiple
breakpoints and examining the values of the variables, then seeing whether the way you
wrote the if statement makes sense.
Part D Multiple conditions
An if can be dependent on multiple conditions connected by && (denoting AND) or ||
(denoting OR).
NOTE each condition has to be able to be evaluated as true or false on its own.
In maths, we can say:
5<x<10
Which is where x is between 5 and 10
But in C++ we have to compare x against the 5 and 10 separately:
if ((x>5) && (x<10))
Add else statements to the first of the tests above, so that if the condition is failed,
an alternative statement is displayed.
Add your own choice of else if statements to add different sets of conditions.
Exercise 2
In this exercise, we shall return to your BMI calculation from last week. (If you have done it
already great! Go online and lookup how to calculate Basal Metabolic Rate using the
Katch-McArdle formula and then set a few values so that you can use if and else if to
display different messages about it.
Part A
Now change your code from that week so that:
For a BMI of less than 12, it displays a message to say Underweight
For a BMI if greater than 25, it displays a message to say Overweight
For a BMI between these two limits, it displays a message to say Practically
perfect
NOTE you must do this with a SINGLE if, else if, else sequence.
Part B user input
We have used cout<<x<<endl; constructs to output the value of a variable to screen.
If we want to get input from a user typing, we use cin>>variable;
So instead of just ASSIGNING a value to the height and weight, we get the variable from
the user typing:
cin>>height; //this takes what the user types and stores it in the variable called height
We probably ought to output something first to the user, to tell them what we want them to
do. This is called a PROMPT:
cout<<Please enter height in metres: ;
// the prompt
cin>>height;
// they enter a sensible value (!)
Get the user to enter the height and weight and store them in the variables.
Then use them to calculate the BMI
CHECK that the program displays the expected response (you can use the
debugger to check the BMI value)
(NOTE what TYPE have we given height? Do we care? WHY?)
that value into an integer variable for each player called Player1 and Player2. (So you
need to write a prompt for the first player, then read in his/her choice, then prompt the
second player, and read in his/her choice. You need to clear the screen between the
players so the second doesnt see what the first typed in).
Then you need to use 'if statements' to check all the cases eg where Scissors beats
Paper, Paper beats Stone, and Stone beats Scissors, and display an indication of whether
Player1 or Player2 won, or whether they tied. So if Player 1 entered 1 (representing
scissors), and Player 2 entered 2 (representing paper), your program would show "Player
1 won!" or something similar.
Modify this program so that it repeats the game until the user decides to stop (while loop).
Followup work
Step 1
The 'if statements' for establishing who won and lost are fairly tedious to write. Because
we are using numbers to represent the 3 possibilities, we can subtract the values
representing the choices and use the result to simply the decision making. So for example
if Player1-Player2 is zero, we have a tie, whereas if Player1-Player2 is -1, Player 1 has
won. (These are obviously not the only possibilities.)
Look up the switch statement. Use different cases for the value of Player1-Player2 to
make decisions as to which response to display. Write yourself a TEST PLAN to verify that
you catch all the cases (ie a list of all the possible values of this variable and the expected
result).
Step 2
Instead of having 2 players entering their choices, you can get the program to play against
you.
Replace the portion of the program where you prompt the second player and take in their
choice, and instead use a random number generator to make the program choice. Look up
the function rand(). To include it in the program you need to add a new directive at the top
of the program. After #include "stdafx.h" add the line:
#include "math.h"
Then you need to limit the range of random numbers so that the choice is 1, 2 or 3. There
are a few ways of doing this. The simplest is to use the MODULUS operator expressed
by the % sign. This is like a division, but instead returns the remainder from an integer
division. If I have a line of code saying:
x = y%3;
then, for example, if y is 0, x takes the value 0; if y is 10, x takes the value 1 (y/3 has a
remainder of 1); if y is 14, x takes the value 2 (y/3 has a remainder of 2).
Further exercises to do AT HOME
DESIGN (plan) programs (and then implement them) using loops to do the following:
Program 1
Generates a countdown from 10 till 0, with a timed pause between each line, that ends
Thunderbirds are go!. To get the delay you can call the function :
Sleep(NNN); //NNN is time in milliseconds
To get access to this function, you need to add the extra directive at the top of the
program:
#include <Windows.h>
Program 2
A program that converts from ounces to grams two versions one that gets the user to
enter the number of ounces and then displays it in grams eg 3.5 ounces =>99.2 grams
The other displays a conversion table for 1 till 10 ounces into grams.
Program 3
Prompt the user to enter the currency conversion rate for pounds per dollar (eg 0.7 pounds
per dollar).
Then display a table showing
Dollar
Pound
1
0.7
2
1.4
Etc.
Read up about break;
Use it (or another method) to ensure the table displays only as far as 10 pounds (not
dollars thats easy).
A program that prompts the user for their age, takes it in, and works out their age in 10,
20,30,40,50 years time.
The program must repeatedly prompt and take in the age until they enter an age that is in
the range of 18 to 40.
So there are 2 consecutive loops:
Loop until age is in correct range (while loop)
Prompt and get the age
Check age against valid limits
Loop over future years 10-50 in increments of 10 (for loop)
Display age and each future date
Program 6
Update your earlier lab program to instead play the Big Bang Theory game of Rock-paperscissors-lizard-Spock. In this case it could generate LOADS of if/else code. Be a LAZY
CODER and try to find a way of making it data driven.
REMEMBER
We expect to see EVIDENCE in the dropbox that you are working outside of lab If you
want feedback on your work, then please show it to your tutor during the next lab.