This blog is under construction

Saturday, 21 April 2012

switch statement

Syntax for switch statement:

switch (expression) {
     case const1:  {
              -----------------------
              <Block 1 Statements>
              -----------------------
              break;
              }
     case const2:  {
              -----------------------
              <Block 2 Statements>
              -----------------------
               break;
              }
     case const3:  {
              -----------------------
              <Block 3 Statements>
              -----------------------
              break;
              }
     default:  {
              -----------------------
              < Statements>
              -----------------------
              break;
              }
}

The switch statement evaluates the expression and checks whether any of its case's integer constant value matches with the expression output.  If any match found, then the program flow will move to that particular case and the statements present in that case will get executed.  Otherwise, the statements present in the default will get executed.

Note:
break statement would transfer the control to the end of switch statement.

Example program for switch statement:
 
  #include <stdio.h>
  int main() {
        int data1, data2, res, ch;
        printf("Enter the operation you want to perform:\n");
        printf("1.add\n2.sub\n3.Multiply\n4.Divide\n");
        printf("Enter your choice: ");
        scanf("%d", &ch);
        printf("Enter your 2 inputs:\n");
        scanf ("%d%d", &data1, &data2);
        // ch is the input from the user
        switch (ch) { 
                case 1:  // 1 is the case's integer constant
                        res =  data1 + data2;
                        break;  // transfers control to end of switch statement
                case 2:
                        res = data1 - data2;
                        break;
                case 3:
                        res = data1 * data2;
                        break;
                case 4:
                        res = data1 / data2;
                        break;
                default:
                        printf("You have chosen wrong choice\n");
                        break;
                }
                printf("Result: %d\n", res);
                return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the operation you want to perform:
  1.add
  2.sub
  3.Multiply
  4.Divide
  Enter your choice:  2
  Enter your 2 inputs:
  100 50
  Result: 50



No comments:

Post a Comment