User Tools

Site Tools


cpp:control_structures:switch

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

cpp:control_structures:switch [2024/02/16 01:04] (current)
Line 1: Line 1:
 +===== 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.
 +
 +<code cpp>
 +#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;
 +}
 +</code>   

on the occasion of the current invasion of Russia in Ukraine

Russian Stop this War
cpp/control_structures/switch.txt · Last modified: 2024/02/16 01:04 (external edit)

Impressum Datenschutz