if..else
In decision making the most common statement used is if..else.
if (test condition)
{
This block is known as if block or true block.
If the condition is true, statement/statements
of this block will be executed.
}
else
{
This block is known as else block or false block
If the condition is false, this block will be executed.
'else' is optional. The control will execute either if block
or else block.
}
else if ladder
Too many if,else block may be very cumbersome.This situation can be avoided using else if ladder.The general form of a else if ladder is :
if ( condition 1)
true block of the above decision
else if ( condition 2)
true block of the above decision
else if (condition 3)
true block of the above decision
............................................
else
default block.This block will be
executed if all the above decisions
returns false.This else is optional
In an else if ladder the conditions are evaluated from the top of the ladder. As soon as true condition is found, the true block associated with the condition is executed and the control leaves the else if ladder and executes the statement following the ladder. If all the conditions are false, then the last else containing the default statements are executed. This final else is optional.
switch statement
The switch statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statement/statements associated with that constant are executed and the control leaves the switch body.
The general form of switch statement is:
switch (variable to be compared with a number of constants)
{
body of switch opens.
case int or char constants:
{
case body opens.’ case' is a keyword. case then space then
the constant value or variable, again space and then:
within the body the statements are kept which are to
be executed when switch variable finds match with
the case constant.
last statement of the case body must be break;
This statement will send the control out of the
switch body.
}
The last case is default: .default is a keyword and
this is optional. If no match is found then the default
body is executed.
This page is on problem solving decision making. If you have any doubt in any program, pl. feel free to put your comments. I am here to clear your doubts.
No comments:
Post a Comment