selection Flashcards
Selection Statements Used to allow your program to
“think” and make logical choices
Logical expressions are used to provide decision-making ability
a they protect the body of a selection statement.
In other words,
you will ONLY perform the body of a selection statement if the logical
expression evaluates to TRUE.
The body of a selection statement uses the
same brackets as the main
function {}. These brackets denote the start and end of a selection
statement.
You can put anything that you want inside of the body of a selection
statement (Ex. Declare variables, do output, ask for input, etc.).
However, they will only be valid within the body of the selection
statement. In other words, once you leave the body it no longer exists.
Independent IF Statements
- Each independent IF statement is processed
and evaluated independently
of any other statements.
Syntax if
if(Logical Expression)
{
Statement(s)
}
- Example:
int temp = 0;temp = 27;
if(temp <= 32)
{
cout «_space;“It is cold outside.” «_space;endl;
}
if(temp <= 55) { cout << "It is cool outside." << endl; }
IF/ELSE Statements
- The IF and ELSE are
dependent on each other
You must choose one or the other. If the first one is true,
then the second one must be false and vice versa
The else statement acts as the
default and therefore NEVER needs
a logical expression.
IF/ELSE Statements syntax
if(Logical Expression) { Statement(s) } else { Statement(s) }
-Example:
int temp = 0;
temp = 27;
if(temp <= 32) { cout << "It is cold outside." << endl; } else { cout << "It is not that cold outside." << endl; }
IF/ELSE IF/ELSE Statements
- This works similar to the IF/ELSE
This is used when you want to extend the number of options
to choose from. You can add as many “else if” as needed
to increase the number of choices.
Each ELSE IF has its own
logical expression
The IF, ELSE IF(s) and ELSE are all
dependent on each other
- You must choose one from the group. The first one that is
evaluated to true is selected even if other logical expressions
in the group are true as well
The else statement acts as the default
and therefore NEVER needs
a logical expression.