Switch Case

At university I was lazy when it came to programming, and relied on IFs, FORs and WHILEs, and didn’t get much further.

Here’s a switch statement. It’s kind of like a IF statement.


int a;

int b;

int c;

switch (a) {

case b:

//code

break;

case c:

//code

break;

default:

//code

break;

}

A quick explanation:

If a is equal to Case b do the code, etc. The breaks are there to exit the loop, otherwise the program will fall to the next one, and eventually output the default too. The default is like else.

A good example of using the Switch Case is a cola machine; the user has to input the number assigned to the drink.


#include <iostream>

using namespace std;

int main()
{
 int input;

 cout<<"1 Coke\n";
 cout<<"2 Water\n";
 cout<<"3 Sprite\n";
 cout<<"4 Fanta\n";
 cout<<"5 Pocari Sweat\n";
 cin>> input;
 switch (input) {
 case 1:
 cout<<"Your Coke is ready!";
 break;
 case 2:
 cout<<"Your Water is ready!";
 break;
 case 3:
 cout<<"Your Sprite is ready!";
 break;
 case 4:
 cout<<"Your Fanta is ready!";
 break;
 case 5:
 cout<<"Your Pocari Sweat is ready!";
 break;
 default:
 cout <<"Error. choice was not valid, here is your money back.\n";
 break;
 }
 cin.get();

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s