# Selection Statements Make a decision based on conditions Allows the computer to be intelligent.

## Presentation on theme: "Selection Statements Make a decision based on conditions Allows the computer to be intelligent."— Presentation transcript:

Selection Statements Make a decision based on conditions Allows the computer to be intelligent

Testing for Conditions Compare two numbers for equality, less than, or greater than x > 0greater than x < yless than x >= 2greater than or equal to x <= 3less than or equal to x == 4equals x != ynot equals

Boolean Values Type bool has two possible values, true or false In C++, bool is the same as int, and true is really 1 or any positive value whereas false is really 0 The names bool, true, and false exist just for the programmers convenience

Evaluating a Comparison In C++, comparisons evaluate to 1 or 0, meaning true or false Comparisons are also called Boolean expressions cout << 5 < 10; // Displays 1 cout << 10 == 10;// Displays 1 cout << 10 != 10;// Displays 0

= and == In C++, == means equals whereas = means assignment // Assume x has the value 10 cout << x == 10; // Displays 1 cout << x = 10;// Sets the value of // x to 10 and displays // 10

Priority of Operators x + y < 3 + z// First arithmetic, then comparison (x + y) < (3 + z)// Add parentheses for clarity

Selection Statements // absolute value if (x < 0) x = -x; // Guard against division by 0 if (x == 0) cout << Error: attempt to divide by 0; else cout << y / x;

Syntax of Selection Statements if ( ) // One-way decision if ( ) // Two-way decision else

With Compound Statements if ( ) {. } if ( ) else {. }

Behavior of Selection Statements ? statement true ? statement false true false statement if ( ) {. } if ( ) else {. }

Logical Operators and Compound Boolean Expressions // see if number is within a range if (x >= 1 && x <= 6) cout << Number is between 1 and 6; // see if number is not within a range if (x 6) cout << Number is not between 1 and 6; &&and ||or !not All Boolean expressions return 1 or 0 in C++

Truth Tables for Logical Operators

Priority of the Operators

Multiway Selection // Run a drawing function based on a character command if (letter == C || letter == c) drawCube(); else if (letter == T || letter == t) drawTriangle(); else if (letter == R || letter == r) drawRectangle(); else cout << Unrecognized commmand;

Switch Statements // Run a drawing function based on a character command switch (letter) { case C: case c: drawCube(); break; case T: case t: drawTriangle(); break; case R: case r: drawRectangle(); break; default: cout << Unrecognized commmand; }

Download ppt "Selection Statements Make a decision based on conditions Allows the computer to be intelligent."

Similar presentations