User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







cpp:control_structures:switch

Switch


Switch is a loop that is used in c++ to find the many scenarios of an event or object. For example, let's test to see the many scenarios of if someone chooses an item from a menu.

#include <iostream>
 
int main() {
   int choice;
 
   cout << "Choose an option:" << endl;
   cout << "1. OJ" << endl;
   cout << "2. Milk"<<endl;
   cout << "3. Water " << endl;
   cout << "4. Soda" << endl;
   cout << "5. Gatorade" << endl;
 
   cin >> choice;
 
   // notice the {}, these are required for switch   
   switch(choice) {
 
      // choosing the OJ option  
      case 1:
          cout << "OJ it is" << endl;
          break;
 
      // choosing the milk option    
      case 2:   
          cout << "Milk it is" << endl;
          break;
 
      // choosing the water option    
      case 3:
          cout << "Water it is" << endl;
          break;
 
      // choosing the soda option  
      case 4:
          cout << "Soda it is" << endl;
          break;
 
      // choosing the gatorade option    
      case 5:
          cout << "Gatorade it is" << endl;
          break;
 
      // this is the default
      // it is used in case none of the cases (scenarios) above match whatever is being tested
      // this is optional
      default:
          cout << "I'm sorry, but we're out of that" << endl;
          break;   
   }   
   return 0;
}
advertising
cpp/control_structures/switch.txt · Last modified: 2013/06/14 16:20 by Anthony

Impressum Datenschutz