Wednesday, 12 November 2014

Control Structures – switch with the examples

Control Structures – switch with the examples:

The use of the switch statement is to check several possible values for the single expression.
This is similar to the nested if- else statement. The syntax for the switch statement is as follows.
switch (expression)
{
  case constant1:
     list of statements 1;
     break;
  case constant2:
     list of statements 2;
     break;
  case constant3:
     list of statements 3;
     break;
  .
  .
  .
  default:
     default list of statements
}
Switch statement evaluates the expression first and latrer checks for the equivalent case.
If the case is valid it evaluates the group of statements under that case. If it finds the break statement the programs jumps to the end of the switch and continues evaluating the next statements.
So the switch is called as selective structure.
 If the value of the expression is not matching to any case it will execute the statements included after the default.
The below is the pictorial representation of the switch.


The switch and the if-else statements have the same behavior.

switch
if-else
switch (expression) {
  case 1:
    statement 1;
    break;
  case 2:
    statement 2;
    break;
  default:
    default statement;
  }
if (condition 1) {
        statement 1;
  }
else if (condition2) {
      statement 2;
  }
else {
   default statement;
  }

Let us practice the switch with the below example



The switch statement is a bit peculiar within the C++ language because it uses labels instead of blocks. This forces us to put break switch selective block or a break statement is reached. Statements after the group of statements that we want to be executed for a specific condition.
If we did not include a break statement after the first case, the program will not automatically jump to the end of the switch selective block and it would continue executing the rest of statements until it reaches either a break instruction or the end of the switch selective block.
switch (expression) {
  case 1:
  case 2:
  case 3:
    cout << "I am at the case 3";
    break;
  default:
    cout << "I am in the default case";
  }
It is possible to compare the expressions against the constants by using switch statements.

No comments: