Answers to questions on switch statements

  1. What is the nested if statement which is equivalent to each of the following switch statements?

    1.          switch (i) {
          case 1:    j =i; 
          			 break;
          			 
          case 2:    j = i*2; 
                       break;
                       
          case 3:    j = i*3; 
                       break;
                       
          default:    j = 0; 
                       break;
                  }
      
      if(i==1) j=i; else
      if(i==2) j=i*2; else
               j=0;
      

    2.          switch (i) {
          case 3:    j = i; 
          			 
          case 2:    j = j*i; 
                       break;
                  }
      
      if (i==3) j=i*i; else
      if (i==2) j=j*i;
      

  2. Add a percentage operator to the calculator, which takes the current (left hand) value and finds the percentage of it given by the next value input. Compile and test the resulting progra
        case '%':    Result = (Result / 100) * Value; 
                     break;
    

  3. Add a default case to the example, which behaves in a suitable way to handle incorrect typing. Test this version also.
        default:    printf("Incorrect operator %c typeed\n", Operator); 
                     break;
    

Back to the questions.


Back to the notes on switch statements.