# 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/not: !.
• And: `&&`.
• Or: `||`.

Unary operator.

Truth table:

Binary operator.

Truth table:

Binary operator.

Truth table:

## Examples

• Write a function which repeatedly queries the user for an input in the range 1...100. The function should return the first valid input.
• Write a function which takes a numeric grade as a formal parameter and prints Great! if the grade corresponds to an A.
• Write a function which takes an integer formal parameter and returns true if the parameter is in the range 1..10 or 20..29 and returns false otherwise.

## 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;
}
```

• The switch expression.
• Case labels.
• The default case.
• The use of break.

# Exercises

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

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