Week 3: Booleans and Conditions
Learning Goals
CONTENTS:
- Learning Goals
- Readings
- Background
- PreQuiz Assignment (due Monday Jan 27 at 9am)
- Recitation
- Recitation Submission Guidelines
- Homework
Readings
Please note the advised readings of “Brief C++ Late Objects” - Cay Horstmann:
- Monday: 3.2, 3.3
- Wednesday: 3.4, 3.5, 3.6
- Friday: 3.3, 3.4, 3.5, 3.6 (re-read the sections, they should make more sense now)
Background
Booleans
Booleans are a special data type that stores only true
or false
. This true or false value can be stored in a boolean variable, or it can be the result of evaluating different expressions.
Relational Operators
A relational operator is a feature of a programming language that tests or defines some kind of relation between two entities. These include numerical equality (e.g., 5 == 5
) and inequalities (e.g., 4 >= 3
). Relational operators will evaluate to either True or False based on whether the relation between the two operands holds or not. When two variables or values are compared using a relational operator, the resulting expression is an example of a boolean condition that can be used to create branches in the execution of the program. Below is a table with each relational operator’s C++ symbol, definition, and an example of its execution.
Operator | Meaning | Example | Counter Example |
---|---|---|---|
> |
greater than | 5 > 4 is TRUE |
4 > 5 is FALSE |
< |
less than | 4 < 5 is TRUE |
5 < 4 is FALSE |
>= |
greater than or equal | 4 >= 4 is TRUE |
4 >= 5 is FALSE |
<= |
less than or equal | 3 <= 4 is TRUE |
5 <= 4 is FALSE |
== |
equal to | 5 == 5 is TRUE |
4 == 5 is FALSE |
!= |
not equal to | 5 != 6 is TRUE |
4 != 4 is FALSE |
Logical Operators
Logical operators are used to compare the results of two or more conditional statements, allowing you to combine relational operators to create more complex comparisons. Similar to relational operators, logical operators will evaluate to True or False based on whether the given rule holds for the operands. Below are some examples of logical operators and their definitions.
Operator |
NAME | type | notes |
---|---|---|---|
<leftOperand> && <rightOperand> |
AND | binary | returns true if and only if both <leftOperand> and <rightOperand> are true |
<leftOperand> || <rightOperand> |
OR | binary | returns true if one or both operands are true |
! <onlyOperand> |
NOT | unary | returns true if the <onlyOperand> is false and false if the <onlyOperand> is true |
Every logical operator will have a corresponding truth table, which specifies the output that will be produced by that operator on any given set of valid inputs. Below are truth tables for each of the logical operators specified above.
AND ( &&
): These operators return true if and only if both operands are True. This can be visualized as a venn diagram where the circles are overlapping.
<leftOperand> |
<rightOperand> |
<leftOperand> && <rightOperand> |
---|---|---|
true | true | true |
true | false | false |
false | true | false |
false | false | false |
OR ( ||
): These operators return True if one or both of the operands are True. This can be visualized as the region of a venn diagram encapsulated by both circles.
<leftOperand> |
<rightOperand> |
<leftOperand> || <rightOperand> |
---|---|---|
true | true | true |
true | false | true |
false | true | true |
false | false | false |
NOT ( ! ): This operator returns the opposite of the operand. This can be visualized as the region of a venn diagram outside the circle. Unlike AND and OR, the NOT operator has only one operand.
<onlyOperand> |
! <onlyOperand> |
---|---|
true | false |
false | true |
You can create truth tables for more complicated expressions by combining elements of these tables. You should begin with columns of the basic variables representing each possible combination of those variables, and then add columns to represent their modified values. For example, if you wanted to create a truth table for !p && q
you could make a column for p
and a column for q
representing all possible combinations of true/false between the two variables. You can then create a third column for !p
, and then perform the &&
operation between the !p
and q
columns instead of the p
and q
columns, like this below:
p |
q |
!p |
!p && q |
---|---|---|---|
true | true | false | false |
true | false | false | false |
false | true | true | true |
false | false | true | false |
You might also choose to represent this intermediate column with a variable as demonstrated in the table below:
p |
q |
r = !p |
r && q |
---|---|---|---|
true | true | false | false |
true | false | false | false |
false | true | true | true |
false | false | true | false |
For simple expressions, you can often work through the truth table in your head. However, knowing how to make truth tables will be helpful when you need more complicated expressions.
Using Booleans
There are two main ways you can use booleans: you can either assign them to a boolean variable, or you can use them directly as a condition (such as in an if statement). If you would like to evaluate a boolean expression and store it in a variable, you can do it like this:
bool myNewBoolean = (4 < 5); // this will evaluate to true
bool mySecondBoolean = (5 == 6); //this will evaluate to false
bool myFinalBoolean = (myNewBoolean && mySecondBoolean); //this will evaluate to false
You can string together increasingly complicated boolean equations either as a combination of boolean variables or as a combination of relational/logical expressions.
Booleans can also be represented using integers, and will print that way by default in C++. As an integer representation, 0
is false
and 1
is true
.
You can build if statements using boolean variables or boolean expressions.
Truthy/Falsy
This section was added Jan 28 to help give more context for intersted students.
It is important to note that computers work on values 1
and 0
. Accordingly the boolean value true
is encoded as a 1
and can be used as a 1
. The expression true + 5
s valid and evalutates to 6
. Likewise false
is encoded as 0
. Don’t take my word for it, compile and run the following program:
#include<iostream>
using namespace std;
int main() {
cout << true + 5 << endl;
}
Some things are actually booleans true
and false
, while some things are not booleans, but can be treated as booleans. We call these “truthy” and “falsy”. Below is a table summarizing a few examples.
type | truthy examples | falsy examples |
---|---|---|
int | 1 1300 |
0 |
double | 12.3 -7.0 |
0.0 |
We can show this with code as follows:
#include<iostream>
using namespace std;
int main() {
int i0, i1, i2;
i0 = 0;
i1 = 1;
i2 = 1300;
double d0, d1, d2;
d0 = 0.0;
d1 = 12.3;
d2 = -7.0;
cout << "1 means truthy, 0 means falsy" << endl;
cout << i0 << ":: " << !!i0 << endl;
cout << i1 << ":: " << !!i1 << endl;
cout << i2 << ":: " << !!i2 << endl;
cout << d0 << ":: " << !!d0 << endl;
cout << d1 << ":: " << !!d1 << endl;
cout << d2 << ":: " << !!d2 << endl;
}
Conditionals
Conditional statements, also known as decision statements or branching statements, are used to make a decision based on condition. A condition is an expression that evaluates to a boolean value, either true or false. Execution in C++ is a good online resource for learning about conditionals in C++.
There are a few types of conditional expressions such as If
statements, If/Else
statements, and If/Else If/Else
statements each more complicated than the prior but also more dynamic way to make decisions in your code. Other tools for making decisions in your code include Switch
statments (that we’ll cover this week) and Ternary
expressions (which we may never cover).
IF Statements
An If
statement in C++ is composed of a condition and a body. The body is executed only if the condition is true. The condition appears inside a set of parentheses following the keyword “if” and the body appears within a set of curly brackets after the condition:
The general format for if statements is:
// NOTE: if is all lowercase
if ( <CONDITION> ){
<BODY>
}
It is good practice to vertically align the closing curly bracket with the start of the if statement, and to indent the body. Examples below:
// BEST FOR NOW
if ( <CONDITION> ){
<BODY>
}
// SOMETIMES USED
if ( <CONDITION> )
{
<BODY>
}
// PLEASE DON'T
if ( <CONDITION> ) {
<BODY>
}
// THAT'S JUST RUDE.
if ( <CONDITION> ) { <BODY> }
The condition is interpreted as a boolean value, either true or false. If-and-only-if the <CONDITION>
holds true
then the <BODY>
of the If
statement is executed
// Here is an if statement that will check
// if a number is negative
// and change it to positive
// (i.e., find the absolute value):
if (num < 0){
// only occurs if num has a negative value
cout << "Changing sign" << endl;
num = -1 * num;
}
// works as expected
if (num == 4){
cout << "Found the number 4" << endl;
}
// works in a weird way
// NOTE the use of a single `=`
if (num = 4){
cout << "Found any number and replaced it with 4!" << endl;
}
IF-ELSE Statements
If statements may be paired with else statements in C++. If the condition associated with the if statement is false, the body associated with the else statement is executed. The else statement body is enclosed in a set of curly brackets:
if ( <CONDITION> ){
<BODY>
// executed when CONDITION is true
}
else{
<BODY>
// executed when CONDITION is false
}
An if statement does not need an else statement, but there must be an if statement before every else statement.
// Here is an if/else statement
// that will check if a number can be a divisor
// before performing division:
if (num == 0) //notice the double equals!{
cout << "Can't divide by 0!" << endl;
}
else{
num = 1000 / num; //integer arithmetic
}
ELSE-IF Statements
Finally, an if statement may also be associated with any number of else-if statements. These statements each have an associated condition and an associated body. The body is executed if the condition is true and the conditions for all preceding if- and else-if statements in the same group are false. An else statement may be included at the end of the group but is not required. The else statement will be executed if all the previous conditions are false.
if ( <CONDITION> ){
<BODY>
}
else if ( <CONDITION> ){
<BODY>
}
else if ( <CONDITION> ){
<BODY>
}
else{
<BODY>
}
This is not logically the same as having multiple sequential if statements.
// These two if statements:
if ( <CONDITION A>){
// do X
}
if ( <CONDITION B>){
// do Y
}
// are NOT logically the same as this if/else-if statement:
if( <CONDITION A>){
// do X
}
else if ( <CONDITION B>){
// do Y
}
In the first code section, both if statements are evaluated. If both CONDITION A and CONDITION B are true, we will do both X and Y. Meanwhile, in the second code block, if CONDITION A is true we will never evaluate CONDITION B, and therefore never do execute that code; here, we will only do X. Therefore, we need to use “else if” only when we want the two conditions to be mutually exclusive.
// Here is an if/else if/else statement
// to tell you if a number is:
// positive,
// 0,
// or negative::
if ( num > 0 ){
cout << "Positive" << endl;
}
else if ( num == 0 ){
cout << "Zero" << endl;
}
else{
cout << "Negative" << endl;
}
Nested If Statements
You can put if statements inside of other if statements (or if/else, or if/else if/else). The meaning of logical expressions can change when you are nesting if statements, so you should think through the truth tables for your if/else statements carefully.
if ( booleanExpression1 ) {
// anything here will evaluate if booleanExpression1 is true
if ( booleanExpression2 ) {
// we will only evaluate this if statement if booleanExpression1 is true,
// and then will only execute this statement if booleanExpression2 is ALSO true
}
}
Nested if statements are essentially performing a logical “AND” operation on the two boolean expressions for the innermost if statement, but if only the first if statement is true you can still do other things.
Common Errors
// Here is some (incorrect) code:
// We've mentioned it 3 times because it's just that common of an issue
int x = 5;
if (x = 1){ // one equal sign: changes value of x, will always evaluate to true
cout << "The condition is true." << endl;
}
cout << "x is equal to " << x << "!" << endl;
The output of this would look like this:
The condition is true.
x is equal to 1
// What you would ACTUALLY want is:
// CORRECT CODE
int x = 5;
if (x == 1) // two equal signs, performs comparison
{
cout << "The condition is true." << endl;
}
cout << "x is equal to " << x << endl;
Which would output:
x is equal to 5
PreQuiz Assignment (due Monday Jan 27 at 9am)
Recitation
Recitation Spot The Error - Problem 1
The code snippet below is supposed to determine if a variable stores a value that is greater than, less than, or equal to 8. Identify the error(s) in the code below, and write the correct line(s).
#include <iostream>
using namespace std;
int main()
{
int num = 6;
if (num > 8) {
cout << "The number is greater than 8." ;
}
else if (num = 8) {
cout << "The number is equal to 8.";
}
else {
cout << "The number is less than 8.";
}
return 0;
}
Recitation Spot The Error - Problem 2
The code snippet below is supposed to classify shapes based on the number of sides into specific categories (triangle, quadrilateral, pentagon, or a general polygon). Identify the error(s) in the code below, and write the correct line(s).
#include <iostream>
using namespace std;
int main()
{
int sides = 6;
if (sides < 2) {
cout << "Invalid input! A polygon must have at least 3 sides." << endl;
}
else if (sides == 3) {
cout << "It is a triangle." << endl;
}
else if (sides == 4) {
cout << "It is a quadrilateral." << endl;
}
else if (sides = 5) {
cout << "It is a pentagon." << endl;
}
else {
cout << "It is a general polygon." << endl;
}
return 0;
}
Recitation Spot The Error - Problem 3
The code snippet below is supposed to determine if a variable stores a value that is equal to zero or not. Identify the error(s) in the code below, and write the correct line(s).
#include <iostream>
using namespace std;
int main()
{
int num = 7;
if (num) {
cout << "The number is zero.";
}
else {
cout << "The number is not zero.";
}
return 0;
}
Recitation Spot The Error - Problem 4
The code snippet below is supposed to determine if a variable stores a value that is smaller than, equal to or larger than zero. Identify the error(s) in the code below, and write the correct line(s).
#include <iostream>
using namespace std;
int main()
{
int num = 0;
if (num<0) {
cout << "The number is less than zero.";
}
else {
cout << "The number is zero.";
}
else if (num>0) {
cout << "The number is greater than zero.";
}
return 0;
}
Recitation Spot The Error - Problem 5
The following code snippet is expected to accept a user provided integer and then state whether that number is even or odd. Identify the error(s) in the code below, and write the correct line(s).
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Provide an integer:" << endl;
cin >> num;
if (num%2){
cout << "The number is even." << endl;
}
else {
cout << "The number is odd." << endl;
}
return 0;
}
Recitation Spot The Error - Problem 6
The following code snippet is expected to accept a user provided character and then state whether the corresponding grade passes or not. Identify the error(s) in the code below, and write the correct line(s).
#include <iostream>
using namespace std;
int main()
{
char grade;
cout << "Provide a grade (A, B, C, D, or F):" << endl;
cin >> grade;
if (grade == 'A' || 'B' || 'C'){
cout << "This is a passing grade." << endl;
}
else if (grade == 'D'){
cout << "This grade passes with conditions." << endl;
}
else {
cout << "This is a failing grade." << endl;
}
return 0;
}
Recitation Hydration Tracking App - Problem 7
Your goal is to drink 7 glasses of water every day, but you often forget to stay hydrated! So you decide to create a hydration tracking app that monitors your water consumption each day and provides feedback on your progress. The program first asks how many glasses of water you drank that day and then displays a message based on your intake. Additionally, it calculates and tells you how many glasses you are left to drink to hit your goal.
The following are the possible messages you will get based on your intake:
- If you drank 3 glasses or less, you get:
You are falling behind! Drink more water! You have X glasses left to drink.
- If you drank more than 3 glasses but less than 7 glasses, you get:
You're doing well! Keep it up! You still have X glasses left to drink
- If you drank 7 glasses or more, you get:
Congratulations! You've hit your water goal for the day! Stay hydrated!
Note that X is the number of glasses left to drink left after subtracting how much water you have drunk already.
Here is a sample run with user input noted:
Recitation Hydration Tracking App - Problem 7.a.: algorithm
Write an algorithm in pseudocode for the program above.
Recitation Hydration Tracking App - Problem 7.b.: examples
Imagine how a sample run of your program would look like. Write at least two examples.
Recitation Hydration Tracking App - Problem 7.c.: boundary conditions
Identify the values that you must test for. We call these values “boundary conditions”.
Recitation Hydration Tracking App - Problem 7.d.: implementation
Implement your solution in C++ using VS Code. Revise your solution, save, compile and run it again. Are you getting the expected result and output? Keep revising until you do. Make you sure you test for the values used in your sample runs, and for the boundary conditions.
Recitation Submission Guidelines
Important: Follow these instructions carefully when preparing your recitation assignments. Your final submission should be in a single document, and the only action required on Canvas is uploading that document.
- Documentation:
- Create a Word/Google doc that includes your submission for all recitation questions. This is the doc you will upload to your canvas assignment.
- Clearly label each question with its corresponding number and include content as applicable (see #2).
- Content to Include:
- Screenshots of Your Code:
- For each question, include a screenshot of your code.(corrected code in case of spot the errors)
- Screenshots of Code Output (if applicable):
- For some longer questions, it might be required to take a screenshot of the code’s output. Include these screenshots as part of your submission.
- Longer Recitation Questions (Multiple Parts):
- Option A:
- Comment your answers directly within your code file.(Spot the errors)
- Take screenshots of the commented code and paste them into your Word document.
- Option B:
- Take screenshots of the unmodified code.
- Write your answers (Free Response/Pseudocode/Edge case identifictation) to the subquestions in the Word document next to the corresponding screenshots.
- Option A:
- Screenshots of Your Code:
- Submission:
- Upload the final Word document to Canvas. This is the only action required on Canvas for your submission.
By following these steps, your submission will be clear, organized, and standardized across all recitation assignments.
Homework
You should complete the following homework using VSCode and the skills that you have learned to author, compile, and execute programs. You should build and fix your code using VSCode. Once you believe you have completed the assignment locally, submit your work on Canvas using the appropriate link for the assignment and the “coderunner” tool.
The coderunner questions match these questions exactly. It will tell you what to do for the problem, give you a few examples of input/output. Give you a space to submit your code.
Homework: Preparing for the Heat
You are planning to go for a run outside, but it’s a hot day. Write a C++ program to determine whether you need to carry extra water based on the temperature.
The program should prompt the user to enter the temperature in degrees Fahrenheit. If the given temperature is above 85°F, display “You need to carry extra water.” as it is considered hot weather for running, and then terminate. If the temperature is 85°F or below, the program will display “You don’t need extra water.” as carrying extra water may not be necessary, and then terminate.
Additionally, the program should perform input validation. If the user inputs a non-positive value for temperature (i.e., 0 or a negative number), the program should display “Invalid temperature.” and terminate.
The following template is provided for your convenience:
#include <iostream>
using namespace std;
int main()
{
// declare all the variables
int temperature;
// prompt the user & get their input
cout << "What is the temperature?" << endl;
cin >> temperature;
// input validation: temperature must be positive
_____________________________ // FILL IN THIS LINE
{
cout << "Invalid temperature." << endl;
return 0;
}
// decide if you need to carry extra water based on the temperature
_____________________________ // FILL IN THIS LINE
{
cout << "You need to carry extra water." << endl;
}
else
{
cout << "You don't need extra water." << endl;
}
return 0;
}
example: temp is 75
example: temp is 90
example: temp is -5
Homework: Ordering Pizza
You’ve decided to order a pizza for dinner. The restaurant you’re ordering from has three sizes of pizza: S, M, and L. Each size has a different base price and price per topping. The prices are indicated in the table below. Create a program to calculate the total cost of your pizza. The program should prompt you for the size of the pizza and the number of toppings, then output the cost.
Size | Base Price | Price Per Topping |
---|---|---|
S | 8.00 | 0.99 |
M | 10.00 | 1.99 |
L | 14.00 | 2.99 |
The input should be a character
(for size) and a non-negative integer (for the number of toppings). The program should accept both lowercase and uppercase inputs for pizza sizes (e.g., s
, m
, l
or S
, M
, L
), and the output should be double
.
Here is an example of a good run of the program:
Note: You can utilize the toupper()
or tolower()
functions to convert the input into either upper or lower case before comparing.
Note: The total cost should be formatted with a two-digit precision. You can use the setprecision()
function with the fixed manipulator from <iomanip>
library to do so.
Bad formatting: 10.8
Good formatting: $10.80
You will also need to perform input validation on the size of the cake – i.e., XL is not valid as demonstrated below.
Observe that we choose to still ask teh user for the number of toppings that they want before stating that the pizza size is not valid
We should also have errors for an invalid number of toppings
And finally we should have an error if neither the pizza size nor the number of toppings are valid.
Homework: Travel
You want to write a program that tells you if you can afford a road trip. In order to do this, you need to know your budget, how far you are driving, and how many nights you will stay.
To calculate the gas money, you estimate the road trip will cost you 16 cents per mile. After computing the gas money, you can determine your budget for each night. If you have less than $20 a night, you cannot afford to go. If you have at least $20 a night, you can afford to go camping during this trip. If you have at least $50 a night, you can afford a cheap motel. If you have at least $100 a night, you can afford a nice hotel.
You should perform basic input validation for all inputs by checking that they are non-negative numbers. If any of the inputs are invalid, the program should display “Invalid input(s).” Otherwise, the program should proceed with the calculations based on the provided values.
example nice hotel:
example cheap motel hotel:
example: outside your budget
example: camping
example: a generic error
Homework: Temperature Changes
You’ve decided to test the temperature outside every morning. Create a program that will tell you if the temperature over the last three days has increased, decreased, or neither. If the temperatures are increasing, print out “It’s getting warmer!”. If the temperatures are decreasing, then print out “It’s getting cooler!”. If the temperatures are not in any order or if two or more temperatures are the same, then print “The temperature is changing unpredictably.”
The user should input 3 non-negative numbers (double
) separated by spaces.
EXAMPLE: warmer
EXAMPLE: cooler
EXAMPLE: unpredictable tempuratures
EXAMPLE: errors (requires only positive values)
Homework: Car Rental
You have decided to go on a weekend road trip with your friends. So, you plan to rent a car for this trip. The car rental company offers many options and has 4 categories. Each type of car has its specific base rate and price per day to rent the vehicle. Write a C++ program that calculates the total cost based on the car type and number of days.
Car Type | Base Price | Price per day |
---|---|---|
A | $80 | $15 |
B | $110 | $25 |
C | $160 | $35 |
D | $220 | $45 |
The total bill is calculated based on the following formula:
- Total = 1.23 X ( base price + no. of days X price per day )
The input should be a character
(for car type), a non-negative integer
(for the number of days you want to rent the car), and the output should be double
.
Ensure you are doing input validation. The user should input car type from one among A, B, C, or D, and the minimum number of days to rent a car is 1. If the car type or the number of days is invalid, display "Please enter valid input."
and exit the program.
Note: The total cost should be formatted with a two-digit precision. You can use the setprecision()
function with the fixed
manipulator from the <iomanip>
library to do so.
Bad formatting: 10.8
Good formatting: $10.80
EXAMPLE: Rent A
for 6
days
EXAMPLE: Rent C
for 11
days
EXAMPLE: Invalid input 1
EXAMPLE: Invalid input 1
Entering on coderunner
Now that you have completed all of the assignment in VSCode, go submit your work via coderunner on Canvas. Be sure to check
your work and return to VSCode as needed if you need to fix anything. Don’t forget to submit this work on coderunner by the deadline to receive credit for this assignment.