You are on page 1of 8

Computer Science Programming SOFT10101

Session 2 Selection using if and repeating using for


Outcome of session

Further work on declaring and using basic variables

Using if/else to control actions in the program

User input of data

Random number function and modulus operator

Using loops to do things repeatedly

Using the debugger to step through a running program


If during the following steps you cannot follow something, or it doesn't work, please check
with your neighbour that you are doing it right. If it still doesn't work, raise your hand and
the tutor will try to help.
NOTE! There will be a dropbox on NOW called Week2. You are EXPECTED to code for 810 hours per week outside class.
So put your programs in the dropbox (just the cpp files, not the whole folder) so that there
is evidence of your activity BEYOND the lab.

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;
}

And what ACTUALLY happens?


If your code does NOT show the hooray line, we will find out why.

Part C using the debugger (VERY IMPORTANT FOR PROGRAMMERS)


If running a program within IDE (Visual Studio), the environment allows you to stop the
progress of the program and check the values of variables, to see if they're what you
expected.
Very useful if writing a complicated set of if statements, and can't work out why it's doing
one rather than another.
(When program is tested and working, we just run the .exe file without Visual Studio.)
1. In your program, find the line that says:
if (bFloat==3.6)

2. In LH margin of the main window, click the left mouse button.


3. This puts red dot in the margin indicating a BREAKPOINT.
(If program reaches this line of code when running, IDE will stop the program at this point)
4. Run the program (start debugging) ie press F5.
5. Program will start and continue until the breakpoint.
6. Visual Studio screen will then show a yellow arrow on top of the red dot.

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))

Create integer variables called, a,b,c,d.


Initialise them to values of 2,4,6,8 respectively
Construct a set of if statements that use multiple comparisons as follows:

Display Test A if a is equal to 2 and b is less than 3


Display Test B if a is NOT equal to 3 and b is greater than 2
Display Test C if c is less than 7 OR d is greater than 9
Display Test D if c is greater than/equal to 6 OR d is less than/equal to 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?)

SYNTAX the while loop


while (condition)
{
// DoSomething lines of code here
}
For example:
int answer =1; //start value
while (answer ==1) //end condition
{
//Prompt and get height and weight
// Do the BMI calculation
//Use if to display an appropriate response
//Prompt and get a value for answer (do they want to try again? 1 for yes, 0 for no)
}
The while loop repeats as long as the condition is true. We frequently use a setup where
we increment a COUNTER inside the loop, and the while (condition) depends on the value
of the counter eg:

int myvalue =1; //start value


while (myvalue <10) //end condition
{
//do something dependant on myvalue
//Increment myvalue
myvalue++; //inc by 1
}
SYNTAX the for loop
'for' is a way of combining the start value, end condition and increment used in the while
loop.
for (initial value; end condition; repeat action)
{
loop statements
}
Initial value here is setting loopCount to zero. In more complex loops, you might initialise
more than one variable but that gets complicated and messy.
End condition, as previously, is when loop terminates it is a boolean experession, though
it does not need its own set of brackets as it does within 'if'.
Repeat action is what happens after the loop statements have been executed in this
case, incrementing loopCount.
Generally, this syntax can be written:
for (expr1; expr2; expr3)
{
statement;
}
and it is exactly equivalent to:
expr1;
while (expr2)
{
statement;
expr3;
}
When to use while or for is largely a matter of preference, though simple counted
situations are more clearly visible with 'for' since all the setup and testing is in one place.
'While' can be more natural for dealing with situations where you want to stop due to some
less predictable condition occurring.

Exercise 3 Scissors, paper, stone


You are to write a program to display the result of two players playing "Scissors, Paper,
Stone". Rather than get the 2 players to enter the whole words for each, you will prompt
them to enter an integer of value 1 for scissors, 2 for paper and 3 for stone. You will read

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

You can include one loop INSIDE another:


Program 4
A program that prompts the user for an integer.
When they enter a positive integer eg 7, it then displays the 7 times table (up to 10 times
7), then prompts for a new integer.
It repeatedly displays times tables (as specified by user input) until they enter 0 instead of
a positive integer.
So it has NESTED loops:
Loop until user enters 0
Prompt and get user number N
Display heading Times table for N (where N is the number they enter)
Loop over range of times table (1 till 10)
Display index and index * N

You can include one loop AFTER another:


Program 5

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.

You might also like