Chapter 3 Flashcards
How is an if-statement used?
If-statements are used to execute different actions depending on the situation at hand.
Format:
if (condition)
{
statement1;
statement2;
}
If the condition is true, the statements are executed, however if they are false, all the code in the braces are skipped.
How does the if-else statement work?
If the condition in the parenthesis is true, statement 1 will be executed. If it is false, the first statement will be skipped and the second statement will be executed.
one of the other block is always executed
Explain the ir-else-if statement.
If condition 1 is true, statement A will be executed, if it is false that first statement will be skipped and will move onto the second condition. If the second condition is true, statement B will be executed otherwise nothing will happen.
Explain relational operators.
Relational operators compare numbers and strings.
Order of least to greatest:
(space) < numbers and symbols < UPPERCASE < lowercase
If two characters are equal, move onto the next character to compare
Ex: “4tom” < “Tom 9” < “joe1” < “joe2”
Explain the combined statement: AND (&&)
This is a conjunction.
EX: (A&&B) both A and B must be true
DO NOT USE THE WORD AND TO REPRESENT AND, YOU MUST USE &&
Explain the combined statement: OR (||).
This is a disjunction.
EX: (A||B) either A or B must be true
It only evaluates as false if both A and B are false
Explain the Boolean operator NOT
Format: ! (statement)
Ex: if (! (x<0)) // equivalent to if (X > =0)
If condition C is true then !C is false.
If condition C is false, then !C is true
What is the precedence of boolean operators?
Parenthesis > Negation > Conjunction > Disjunction
*Recommended: (A || (B && C) )
What does it mean that the boolean operators are lazily evaluated?
Boolean operators are evaluated from left to right. If the first expression is false, then the second expression will never be evaluated.
What are nested branches?
Nested branches are when a decision is contained inside the branch of another decision statement.
Ex:
if (number > 1000) {
if (number % 2 == 0)
cout «_space;“A large even number”;
else cout «_space;“A large odd number;
}
else {
if (number % 2 == 0)
cout «_space;” A small even number”;
else cout «_space;” A small odd number”;
How do we use if- else statement for input validation?
We use them to check if the input is within a required range
Ex:
double x;
cout «_space;“Input a positive number: ”;
cin»_space; x;
if ( x>0 )
{ cout «_space;”The square root of ”
«_space;x «_space;“ is ” «_space;sqrt(x);
}
else
{ cout «_space;“Wrong input.”; }