Switch statement

We have seen that when we have many alternatives and we have to select one of them, we can use an if statement to control the selection. However, the complexity of such a program increases dramatically when number of alternatives increases. To, come out from these situations C has a built-in multiway decision statement known as "switch". It tests the value of a given variable or expression against a list of case values and when a match is found, a block of statements associated with that case is executed.

The general form of a switch statement is:-


 "switch(expression)
   {
     case value 1:
         block 1
         break;
     case value 2:
         block 2
         break;
     case value 3:
         block 3
         break;
      ...................
      ...................
     default:
       default statement
        break;
    }
  statement x; "
Here values are also called as "Case labels". Each of the values should be unique within a switch statement. block 1,block 2... are statement list to be executed, associated with the case labels. When the switch is executed, the value value of the expression is successfully compared against the values (value 1, value 2...). If a case is found such that value of case matches with the value of  the expression, then the block of statements associated with that case are executed.
 The break statement at the end of each block, tells the end of that block and cause an exit from the switch statement, transferring the control to the statement x.
 If the value of the expression does not match with the value of any case then, a case label,namely default, will be executed. But if default is not present then, no action takes place if all matches fail the control will pass to statement x.

We can easily understand the flo of control of switch statement from its flowchart.:-
flowchart of switch case statement
Rules for switch statement:-

1.Case label must be unique.
2.Case label must end with semicolon.
3.The break statement is optional.
4.The default label is also optional.
5.The case label must end with colon(:).


Example:-

--------------------------
--------------------------
index = marks/10;
switch(index)
{
  case 4:
   grade = "Honours";
   break;

  case 3:
   grade = "First division";
   break;

  case 2:
   grade = "Second division";
   break;

  case 1:
   grade = "Third division";
   break;

 default:
  grade = "Fail";
  break;
}
printf("%s\n", grade);
-----------------
-----------------

Here  we assigning the value to grade, using switch statement.

  







Comments

Popular posts from this blog

Components of C language

Decision making using if statement

How to make payment for final certificate, migration, provisional for the students of last semester of ptu?