If Statements and Boolean Expressions
Created 3 years ago
Duration 0:07:50
150
A short (7 minutes or so) review of if statements and Boolean expressions followed by three Code Hunt code duels to try out how well you know the material.

Embed

Social
Select the file type you wish to download
Slide Content

Slide 1  If Statements and Boolean Expressions

Slide 2  Boolean Expressions
 Evaluate to a value of true or false
 Use relational or equivalence operators
 Boolean operators like AND and OR

Slide 3  Relational Operators
 < Less than
 > Greater than
 <= Less than or equal to
 >= Greater than or equal to
 == Equals Not to be confused with the assignment operator =
 != Not equal to

Slide 4  Boolean Operators
  Or as in if a equals b or b equals c
 if (a == b  b == c)
 If either comparison is true than the equation is true. If both comparisons are false than the whole equation is false
 && And as in if a equal b and b equals c
 If (a == b && b == c)
 If either comparison is false than the equation is false. Both comparisons must be true for the equation to be true

Slide 5  Simple if statement
 if (coin == 0)
 MessageBox.Show("Heads");
 If the value of coin is 0 then a message box is displayed. If coin has a value of anything else nothing is displayed.

Slide 6  Adding the else option
 if (coin == 0)
 MessageBox.Show("Heads");
 else
 MessageBox.Show("Tails");
 If coin holds a 0 then Heads is displayed otherwise Tails is displayed

Slide 7  Code blocks
 Enclosed in curly brackets { }
 Allow multi statements to be treated as a single block of code
 Recommended even for single statement “blocks”
 May be used with simple if statements or more complex if/else and if/else if/else statements

Slide 8  Adding code blocks
 If (coin == 0)
 {
 heads++;
 MessageBox.Show("Heads");
 }
 else
 {
 tails++;
 MessageBox.Show("Tails");
 }

Slide 9  Else IF
 if (coin == 0)
 {
 heads++;
 MessageBox.Show("Heads");
 }
 else if (coin == 1)
 {
 tails++;
 MessageBox.Show("Tails");
 }
 else
 MessageBox.Show("Whoops");

Slide 10  Boolean expression – OR Operator
 if (coin == 1  coin == 0)
 MessageBox.Show("Good roll");
 If either comparison is true the message is displayed.
 Only if neither comparison is true is nothing displayed

Slide 11  Boolean expressions – And operator
 if (coin == 1 && last == coin)
 MessageBox.Show("Two tails in a row");
 The message is displayed only if both comparisons are true
 If the first comparison is false the second comparison will not be tried
 This is called short circuiting

Slide 12  Let’s Start With the Code Hunt Puzzles
 Click on the Capture Code button to test the code