Thursday, November 7, 2013

If – Elseif – Else & Switch - Case




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
  1. switch can only check of equality
  2. switch only looks for match between the values of the expression with one of its case constant values. No two case constant can have identical values. Use of switch is more convenient than multiple nested if.
  3. When the case constant match with criteria given computer start from that point continue performing each case even its not satisfied the condition, so its required jump statement like break to jump from the table. Thus its run faster than if construct.
  4. In switch-case only integer and character allowed.
if-else-if-else
  1. if can evaluate using any type of relational operators (checks in ranges) and return type is boolean.
  2. if-else statement uses series of expression involving unrelated variables.
  3. No jump statement can be given for if statement. It check each condition even after it’s found its match, so it’s slower than switch-case.
  4. All available data types can be tested using if-else-if-else.


No comments: