Sunday, January 18, 2009

CONDITIONAL STATEMENTS..
BY: MARY TRISHIA V. TABIGUE
. conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified condition evaluates to true or false
if...else Statement
Use the if statement to execute a statement if a logical condition is true. Use the optional elseif statement looks as follows: clause to execute a statement if the condition is false. An
if
(condition)
statement_1
[else
statement_2]
If condition evaluates to true, statement_1 is executed; otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.
You may also compound the statements using else if to have multiple conditions tested in sequence;
if (condition)
statement_1
[else if (condition_2)
statement_2]
..
[else if (condition_n_1)
statement_n_1]
[else
statement_n]
To execute multiple statements, use a block statement ({ ... }) to group those statements. In general, it is a good practice to always use block statements, especially in code involving nested if statements:
if (condition) {
statements_1
} else {
statements_2
}
switch Statement
A switch statement allows a program to evaluate an expression and attempt to match the expression's value to a case label. If a match is found, the program executes the associated statement. A switch statement looks as follows:
switch
(expression) {
case label_1:
statements_1
[break;]
case label_2:
statements_2
[break;]
...
default:
statements_def
[break;]
}
The optional break statement associated with each case clause ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

No comments: