C++ Tutorial 05 - Switch Case

  • Selection methods –

    1.    If/else/else –if
    2.    Switch

  • A switch statement allows a variable to be compared against a list of values for equality. Each value is referred to as a case, and each switch case is compared to the variable that is being true.

 

            switch(expression) {
              case
 01:
                
// code block
                
break;
              
case 02:
   
             // code block
                
break;
              
default:
   
             // code block
             }

 

Rules for use Switch Case

  1.    Switch expression is integer or character (byte, short, int, char……. etc.)
  2.    Use any number of case statements within a switch.
  3.    Data type must match between switch and cases.
  4.    When the variable matches, expressions are executed until a “break” is meet.       (explain by follow test code.)
  5.    A switch statement can have an optional default case, which must appear at the   end of the switch.

 

Flow Diagram

Flow chart of Switch case of c++


 

Code 01:


#include <iostream>

using namespace std;

 

int main () {

   char department;

  

   cin >> department;

 

   switch(department) {

      case 'A' :

         cout << "department A" << endl;

         break;

      case 'B' :

      cout << "department B" << endl;

         break;

      case 'C' :

         cout << "department C" << endl;

         break;

      case 'D' :

         cout << "department D" << endl;

         break;

      default :

         cout << "Sorry...you entered Invalid department" << endl;

   }

   cout << "Your department:  " << department << endl;

 

   return 0;

}



Code 02: Study output results without break.

Note :

           Use toupper(_) to convert lowercase to uppercase.

 

#include <iostream>

using namespace std;

 

int main () {

   // local variable declaration

   char department1;

  

   cin >> department1;

  

    // Use toupper

   char department = toupper(department1);

 

   switch(department) {

      case 'A' :

         cout << "department A" << endl;

      case 'B' :

      cout << "department B" << endl;

      case 'C' :

         cout << "department C" << endl;

      case 'D' :

         cout << "department D" << endl;

      default :

         cout << "Sorry...you entered Invalid department" << endl;

   }

   cout << "Your department:  " << department << endl;

 

   return 0;

}



Post a Comment

أحدث أقدم