You are on page 1of 8

C++: Conditional

Branching
CMPT 111
Quick Refresher
true
false
if (condition)
{
do something when true
}
Quick Refresher
if (condition)
{
do something when true
}
else
{
do something when false
}
true false
Quick Demo
Guessing game.
int guess;
cout << "Enter a whole number between 1 and 10: << endl;
cin >> guess;
if (guess == 4)
{
cout << "Correct!!!" << endl;
}
else
{
cout << You missed!!" << endl;
}
cout << Thank you for playing << endl;
Exercise #1
Write C++ code that will read in a floating point number
and print out the absolute value of that number.
Example run (red text entered by user):
Please enter a number:
-7.6
The absolute value is: 7.6
Exercise #2
Write C++ code that will determine whether a point is
inside a rectangle.
Example run (red text typed by user):
Center of the rectangle, separated by a space:
5.5 -6.5
Width & height of the rectangle, separated by a space:
10 30.2
Coordinates of the point, separated by a space:
0 0
No
height
width
Yes
No
center
Exercise #3: Bomb Defusing!
Write C++ code that will ask for a colour to be typed in, read
in the colour, and print out (without the quotation marks):
BOOM!! if the words yellow or green are entered
You defused the bomb if blue is entered; or
Thats not a wire if any other word is entered.
Example runs (red text entered by user):
Enter a colour of wire to cut:
yellow
BOOM!!
Enter a colour of wire to cut:
orange
That's not a wire
Enter a colour of wire to cut:
Yellow
That's not a wire
Demo
Comparing floating point values for equality.
Should never use == to compare floating point values.
Rounding error can give false negatives.
To compare whether A equals B, use:
for a small . Ex: = 0.0001
See: floatcompare.cpp
A B <

You might also like