# Conditionas and Logical Expressions

• We are done with our basic study of data structures (almost)
• We are about to begin our study of control structures (almost)
• To this point, the flow of control in our program has been simple
• We executed the first statement
• We executed the second statement
• ...
• We executed the last statement
• It has been essentually sequential or linear.
• We will soon study a selection, or branching structure
• The computer will decide which statement or set of statements to execute baised upon the value of an expression that it evaluates.
• But first, a new data type
• Type bool
• reserved word: bool
• bool flag;
• values : true, false;
• bool flag1 = false, done = true;
• bools are used directly, but more frequently indirectly
• Operations on bools
• && logical and, both must be true for the result to be true
• true && true -> true
• true && false -> false
• false && true -> false
• false && false -> false
• || logical or, one or the other or both must be true
• true || true -> true
• true || false -> true
• false || true -> true
• false || false -> false
• ! uniary not, flip the value.
• ! true -> false
• ! false -> true
• Operations that produce bools
• ==, are the two operands the same
• !=, are the two operands different
• >, >=, is the first greater than, greater than or equal to, the second
• <, <= , less than, less than or equal to
• For most types, (int, char, string, float, bool, ...)
• 3 > 4 -> false
• 'c' < 'd' -> true
• "Hello World" == "Hello World" -> true
• Combining these
• (x<-4) || (x>4)
• (day == "Monday") && (hour > 7)
• When you compare characters, you compare the ascii value of that character.
• So 'A' < 'a' -> true
• 'a' > 'b' -> false
• When you compare strings,
• If the compare the values at position 0, if they are different report this, and exit, if they are the same compare the values at position 1, ...
• If one string ends before the second and they are the same up to that point, the smaller is less
• If they are the same the entire way through, they are equal
• "Hello" < "hello" -> true
• "Hello" < "HEllo" -> false
• "Hello" < "Hello World" -> true
• When you compare ints it is as you expect.
• It is dangerous to compare floats, roundoff error will cause strange behavior.
• it is better to do something like
• fabs(x-y) < 0.001
• then x < y
• try 1.0/3.0 + 1.0/3.0+1.0/3.0 == 1
• Short circuit evaluation
• (4 == 1) && (7 < ??? ) will always be false, so it does not even look at the second part
• (4 == 4) || (????) will always be true, ...