CIS 150 Tests

Objectives

  • Use the bool data type
  • Use relational operators
  • Use logical operators
  • Evaluate expressions using relational and logical operators
  • Combine test expressions

Boolean values

  • Named after George Boole (1815 - 1864)
  • Boolean values are either true or false
  • The bool data type is used in C++ to hold Boolean values
  • C++ has keywords for true and false
  • true evaluates to 1 in C++
  • false evaluates to 0 in C++
  • Technically, any non-zero value that can be converted to a bool is considered true by C++.
  • Example declaration: bool done;
  • Example initialization: bool done = false;

Relational operators

  • There are six relational operators. Assuming a and b are variables:
    • a < b means a less than b
    • a <= b means a less than or equal to b
    • a > b means a greater than b
    • a >= b means a greater than or equal to b
    • a == b means a equal to b
    • a != b means a not equal to b
  • Testing to see if someone passed a class (by percentage): percent >= 0.6
  • Testing to see if overtime should be paid: hours > 40
  • Testing for the letter Q: ch == 'Q'
  • Testing to see if two passwords are different: pass1 != pass2
  • Testing to see if it is below freezing: temp < 32
  • Testing to see if pressure is safely at or below 100 psi: psi <= 100

Logical operators

  • There are three logical operators. Assuming a and b are bool variables:
    • a && b means a AND b
    • a || b means a OR b
    • !a means NOT a
  • There are also three keywords which do the same thing. Assuming a and b are bool variables:
    • a and b means a AND b
    • a or b means a OR b
    • not a means NOT a
  • a && b is true only if a and b are both true, otherwise it is false
  • a || b is true if either a or b is true, otherwise it is false
  • !a is true if a was false, otherwise it is true
  • Note: a || b is true when both a and b are true
  • Note: a && b is false when both a and b are false
  • The order of precedence is !, then &&, then ||

Combining tests

  • Checking for a temp between 65 and 80 (WRONG way): 65 <= temp <= 80
  • Checking for a temp between 65 and 80 (RIGHT way): (temp >= 65) && (temp <= 80)
  • Checking if a non-salaried worker is below forty hours: : (salaried == false) && (hours < 40)
  • Checking if a non-salaried worker is below forty hours: : !salaried && (hours < 40)
  • Checking if a worker is either salaried or below forty hours: : (salaried == true) || (hours < 40)
  • Checking if a worker is either salaried or below forty hours: : salaried || (hours < 40)
  • Checking to see if a letter grade is passing: (grade == 'A') || (grade == 'B') || (grade == 'C') || (grade == 'D')
  • Checking to see if a user entered an upper or lower case Y: (input == 'Y') || (input == 'y')
  • Checking to make sure gender is either M or F: (gender == 'M') || (gender == 'F')
  • Checking to see if gender is neither M nor F: (gender != 'M') && (gender != 'F')