Charlotte Curtis January 24, 2024
if (boolean_expression) { // code to execute if true } else { // code to execute if false }
if-else
Textbook Sections 2.4, 3.1-3.2
bool
int
double
bool thunder_only_happens_when_its_raining = true;
bool is_valid_account_number(int account_number);
if (temperature < 0) { cout << "It's freezing!\n"; }
false
0
true
1
char
char c; cin >> c; bool is_valid = c == 'y' || c == 'Y';
and
&&
or
||
not
!
Example: assign a boolean timed_out that is a function of two ints: total_time and num_records.
timed_out
ints
total_time
num_records
timed_out should be true if the time per record exceeds 1 second, and false otherwise.
cout
In Python, print is a function, so the whole expression is evaluated first:
print
print(x > 0 and x < 10) # prints True or False
In C++, << is an operator:
<<
cout << x > 0 && x < 10; // what happens?
Easiest solution: use parentheses, or assign to a variable:
cout << (x > 0 && x < 10);
if
{}
boolean_expression
=
==
if (x > 0) cout << "x is positive\n";
else
if (x > 0) cout << "x is positive\n"; else cout << "x is negative\n";
Just like Python, you can nest if statements inside each other:
if (is_valid_account_number(account_number) { if (max_disk_usage > allotment) { // surcharge calculation } }
else if
if x > 0: print("x is positive") elif x < 0: print("x is negative") else: print("x is zero")
if (x > 0) { cout << "x is positive\n"; } else if (x < 0) { cout << "x is negative\n"; } else { cout << "x is zero\n"; }
elif
;
if (x > 0); cout << "x is positive\n";
if (x > 0) if (y > 0) cout << "x and y are positive\n"; else cout << "x is negative\n";
In the following code snippet, x has a value of 15. What is the output?
x
Fizz
Buzz
FizzBuzz
if (x % 3 == 0) cout << "Fizz"; if (x % 5 == 0) cout << "Buzz";
What is the output of the following code snippet? x is again 15.
x is 0
x is 0 Try again
Try again
if (x == 0) cout << "x is 0\n"; cout << "Try again\n";
C++ does not restrict you to a single return statement in a function:
return
double relu(double x) { if (x > 0) return x; else return 0; }
A "guard clause" is an if statement that returns early if inputs are invalid
bool is_valid_account_number(int account_number) { if (account_number < 0) { return false; } // rest of function }
while condition: # code to execute
while (condition) { // code to execute }
while
int x = 1; // Initialization while (x <= 100) { // Condition if (x % 3 == 0) cout << "Fizz"; if (x % 5 == 0) cout << "Buzz"; cout << "\n"; x++; // Update }
for
for i in range(10): # code to execute
for (int i = 0; i < 10; i++) { // code to execute }
Since FizzBuzz is counting from 1 to 100, it's a good candidate for a for loop:
for (int x = 1; x <= 100; x++) { if (x % 3 == 0) cout << "Fizz"; if (x % 5 == 0) cout << "Buzz"; cout << "\n"; }
Textbook sections 3.3-3.4
Do a demo with printing/reading input
Give some time to think about it, then implement
Demonstrate fighting emacs over indentation
Ask for prediction, then show what happens