Complex Conditions and the switch Statement

Tom Kelliher, CS17

Apr. 15, 1996

The Conditional Operator

C/C++'s only trinary operator!

(expression_1) ? expression_2 : expression_3

Examples:

int i, j;
int largest;

cout << "Enter two integer values: ";
cin >> i >> j;
largest = (i > j) ? i : j;
cout << largest << " is the largest value you entered.\n";

int sodaCount;

cout << "How many sodas do you want? ";
cin >> sodaCount;
cout << "You have requested " << sodaCount 
     << ((sodaCount == 1) ? "soda.\n" : "sodas.\n");

Complex Predicates

Simple predicates connected with logical operators:

Complement

Unary operator.

Truth table:

And

Binary operator.

Truth table:

Or

Binary operator.

Truth table:

Examples

Equivalent Predicates

!(a == b)   -->   a != b
!(a != b)   -->   a == b
!(a < b)    -->   a >= b
!(a <= b)   -->   a > b

!(expr1 && expr2)   -->   (!expr1) || (!expr2)
!(expr1 || expr2)   -->   (!expr1) && (!expr2)
How could we prove these?

Operator Precedence

  1. ()
  2. Unary: + - ++ -- (type) ! (right assoc.)
  3. * / %
  4. Binary: + -
  5. << >>
  6. < <= > >=
  7. == !=
  8. &&
  9. ||
  10. ?: (right assoc.)
  11. = += -= *= /= %= (right assoc.)

Multiway Selection and the switch Statement

We already have multiway selection with the if:

char letterGrade(int numberGrade)
{
   if (numberGrade < 60)
      return 'F';
   else if (numberGrade < 70)
      return 'D';
   else if (numberGrade < 80)
      return 'C';
   else if (numberGrade < 90)
      return 'B';
   else
      return 'A';
}

switch statement allows you to ``jump'' to a label in a following compound block.

break statement allows you to ``jump'' out of a compound block --- only for loops and switch blocks.

Example:

int n;

cout << "Enter n: ";
cin << n;

switch (n)
{
 case 1:
 case 2:
   cout << "**\n";
   break;

 case 3:
   cout << "***\n";
   break;

 case 4:
 case 5:
 case 6:
   cout << "****\n";
   break;

 default:
   cout << "******\n";
   break;
}

Exercises

Exercises 2, 6, 7, and 10 on pg. 421.



Thomas P. Kelliher
Sat Apr 13 11:57:48 EDT 1996
Tom Kelliher