IF STATEMENTS
syntax
if statement:
if (logical expression)
statement
if else statement:
if (logical expression)
statement
else
statement
A logical expression is an expression that evaluates
to be either true or false
statement - is a single statement or a compound
statement
a compound statement is is a block of statements
enclosed in curly braces
example of a compound if statement:
if (logical expression)
{
statement1
statement2
...
statement n
}
All n statements will execute if the logical expression is true and not execute
if the logical
expression is false.
Keep in mind that a statement could be another if statement. This
would be called a nested
if statement
many scenarios arise (listed are just a few)
if (logical expression)
if (logical expression)
statement
if (logical expression)
statement
else
if (logical expression)
statement
if (logical expression)
{
statement1
statement2
if (logical expression)
{
statement1
statement2
{
else
statement
}
else
if (logical expression)
statement
SWITCH STATEMENT
We use a switch statement when we have a number of specific alternatives
to choose from.
syntax
switch ( expression)
{
case value1:
statements
break;
case value2:
statements
break;
.
.
.
case value n:
statements
break;
default: statements
}
Some important things to note about switch statements:
the expression can only be of an integral
type
each valuei must be an integral constant
or a literal
the break statement will cause you to exit
the switch statement (jump down to the point following
the ending }. If you forget a break you will
drop down into the next case and execute that
code.
example switch statement
let x, y and z be in int variables previously declared
switch (x)
{
case 1: cout << y << " +
" << z << " = " << y + z << endl;
break;
case 2: cout << y << " -
" << z << " = " << y - z << endl;
break;
case 3: cout << y << " *
" << z << " = " << y * z << endl;
break;
case 4: if (z == 0)
cout << "Cannot divide as denominator
is 0" << endl;
else
cout << y << " /
" << z << " = " << y / z << endl;
break;
default: cout << "you did not
make a valid selection" << endl;
}
if x has the value of 1, case 1 will execute
if x has the value of 2, case 2 will execute
if x has the value of 3, case 3 will execute
if x has the value of 4, case 4 will execute
if x has another value, the default case will execute