Each control statement is one logical statement, which often encloses a block of statements in curly braces {}.
The if else statement can be used in following ways:
a) if ..else
b) if .. elseif .. else
c) if .. elseif .. elsif .. elsif .. else
The switch statement can be used in following ways
a) switch (expression)
b) case a:
c) case b:
d) defualt:
In the following example code we will show you how to use the if statements.
Another example of switch statement also shows how to use the switch statements correctly.
Indenting is essential. Four spaces is most common.
if Statement
//----- if statement with a true clause
if (expression) {
statements // do these if expression is true
}
//----- if statement with true and false clause
if (expression) {
statements // do these if expression is true
} else {
statements // do these if expression is false
}
//----- if statements with many parallel tests
if (expression1) {
statements // do these if expression1 is true
} else if (expression2) {
statements // do these if expression2 is true
} else if (expression3) {
statements // do these if expression3 is true
. . .
} else {
statements // do these no expression was true
}
|
switch Statementswitch chooses one case depending on an integer value. This is equivalent to a series of cascading if statements, but switch is easier to read if all comparisons are against one value. The break statement exits from the switch statement. If there is no break at the end of a case, execution falls thru into the next case, which is almost always an error.
switch (expr) {
case c1:
stateme |