The if-then-else is
the basic the control flow statement and exercised in all programming
languages. It tells the program to execute a certain part of the program if a test condition is true
otherwise perform some other directed
part of the program if test condition is fail. We know that program
executed in sequential order from top to bottom. However, often program may
need to produce a result when certain condition is satisfied.
The statement starts
with if, followed by the condition to be tested for inside a pair of brackets. The
codes are written within a pair of optional curly bracket. When the Boolean
expression evaluates to true then the block of code inside the if statement
will be executed otherwise it will follow elseif or else.
Syntax:
if(var (relational operator)
var/value)
{
//some code
}
else if(var (relational
operator) var/value)
{
//some code
}
else
{
//some code
}
A switch statement
gives option to select from a range of values for variables. Switch statement
is useful in a program when one of several choices need to be selected. Switch
is more simple and compact. Switch only works with int, char, byte and short
data types. A break statement is necessary after each case but not compulsory.
"Fallthrough" will be affected in absence of break after any case. "fall through" condition happens
when a case in a switch statement doesn't end with a break or return or any
other control-breaking statement. In such case program execution continues
beyond the current case and fall to the subsequent case block.
Syntax
:
switch(variable)
{
case value1: //block;
break;
case value2: //block; //absence of break
case value3: //block;
break;
default://error message;
}
Difference between switch-case
and if-else if-else
switch-case
|
if-else-if-else
|
No comments:
Post a Comment