Equality and Relational Operators
- = = != //be careful with = =
- < > <= >=
- Boolean expressions: not, and, or
- Precedence revisited
Boolean Data Type
- type name is bool
- Values are true and false
- False is equivalent to a 0
- True is anything but a 0
- both of these sets b2 to false:
- bool b2 = false;
- bool b2 = 0;
- all of these set b1 to true:
- bool b1 = true;
- bool b1 = 1;
- bool b1 = -81;
- bool b1 = 5.6;
Conditional Programming - One-Way ifs
- Not sequential
- When needed to choose between two (or more) alternatives
- One-Way ifsyntax
for single statements
if ( condition )
statement;
- examples of C++ code
if ( input_num < 0 )
cout << "Error message";
- One-Way if syntax for multiple statements
if ( condition )
{
statement1;
statement2;
}
- examples of C++ code
if ( grade == 100 )
{
cout << "Excellent job\n";
bonus = 1;
}
try some:
- ask user for there 3 exam scores, calculate the average and report if
they get above the HIGH_SCORE of 92
- ask the user for 2 numbers and divide them if the second isn't 0
IF-ELSE syntax
- single statements
if ( condition )
statement;
else
statement;
- examples of C++ code
if (x < 0 )
cout << "negative number\n";
else
cout << "non-negative number\n";
- multiple statements
- examples of C++ code
- used for error checking
- used for alternate selections
- C++ uses short circuit evaluation
- Integers can be used in place of boolean
try some:
- Ask user for a number report if it is even or odd
- Ask the user for there exam score and report if it is passing (60.0 or above)
or failing
Nested IFs
- More than two possible actions
- Second if can be nested inside of the 1st "if" part or the 1st "else" part
- Examples
-
if ( x <0 )
cout << "negative number\n";
else
if ( x == 0 )
cout << "zero\n";
else
cout << "positive number\n";
ELSE IFs
if (x < 0 )
cout << "negative number\n";
else if (x == 0)
cout << "zero\n";
else
cout << "positive number\n";
try some:
- Ask the user for their exam score and report if it is
an A (90.0 or above), B, C, D, or F
- Divide two numbers the user enters. If the second number is 0, ask the user
to re-input the number and then perform the division.
Characters and Strings
Examples and Typical Errors
- Errors
- Forgetting braces
- putting ; after ()
- Using = instead of ==
- Redundant testing of boolean values
Multi-way selection: The Switch statement
- Used in place of if-elseif-elseif
- Syntax
switch ( variable)
{
case1: statements;
break;
case2: statements;
break;
. . .
casen: statements;
break;
default: statements;
}
try some: