We have already discussed the eighth chapter which is the conditional statements. I learned that conditional statements are statements that check an expression then may or may not execute statements depending on the result of the condition. There are 6 kinds of conditional statements: (1) If Statement, (2) If-Else Statement, (3) Nested-If Statement, (4) If-Else-If Ladder, (5) Switch statement, and (6) Nested Switch Statement.
The general form:
if ( expression)
statement;
Expression is relational or Boolean expression that evaluates to a TRUE (1) or FALSE (0) value. Statement may either be a single C Statement or a block of C statements. In an if statement, if the expression evaluates to (1), the statement that forms the target of the if statement will be executed. Otherwise, the program will ignore the statement.
If an if-else statement, if the expression is (1), the statement after the if statement will be executed. Only the code associated with the if or the code is associated with the else executes, never both. In C, the else is linked to the closest preceding if that does not already have an else statement associated with it. The general form of the if-else statement with block of statement is:
If (expression)
{
statement_sequence;
}
else
{
statement_sequence;
}
A common programming construct in C is the if-else- if ladder. In an if-else-if ladder statement, the expression are evaluated from the top downward. As soon as a true condition is found, the statement associated with it is executed and the rest of the ladder will not be executed. If none of the condition is true, the final else is executed. The final else is optional, you may include this part if needed in the program or you may not include if not needed.
The switch statement is a multiple-branch decision statement. In a switch statement, a variable is successively tested against a list or integer or character constants. If a match is found, a statement or block of statement is executed. The default part of the switch is executed if no matches are found. The break statement is used to terminate the statement associated with each case constant. It is a C keyword which means that at that point of execution, you should jump to the end of the switch statement by the symbol }.
The general form of the nested switch statement is:
switch (variable)
{
case constant:{
switch (variable)
{
case constant1:
statement sequence_1;
break;
case constant2:
statement_sequence_2;
break;
}
break;
}
case constant2:
statement sequence;
break;
default:
statement sequence;
}
No comments:
Post a Comment