C++ part 4 – switch statement

In post, we are going through the switch statement. Switch statement is very similar to if statement that we went through in the previous C++ post. The only difference between switch statement is that many people do not use it anymore because it is considered to be a bit outdated way to do algorithms and I will tell you why.

Switch statements only take one value to consideration although many cases will be implemented in one switch statament. The below is the example of one switch statement.

#include <iostream>
using namespace std;
int main()
{
    int choice;
    
    cout << “Please pick a number from 1-5: ” << endl;
    cin >> choice;
    
    switch(choice)
    {
      case 1:
           cout << “You have chosen: ” << choice << endl;
           break;
      case 2:
           cout << “You have chosen: ” << choice << endl;
           break;
      case 3:
           cout << “You have chosen: ” << choice << endl;
           break;
      case 4:
           cout << “You have chosen: ” << choice << endl;
           break;
      case 5:
           cout << “You have chosen: ” << choice << endl;
           break;
    }
    system(“PAUSE”);
    return 0;
}

and below is the picture of one outcome

example1

Basically what happened in the above example is that if the user entered 3, the program will jump in the part of the code that I have highlighted below


    switch(choice)
    {

where the switch statement will go through case by case, what the user has entered and when it finds for example in the code below


      case 3:
           cout << “You have chosen: ” << choice << endl;
           break;

where the “case 3:” means that if the value is 3, do something. In our example it will print on the console what you saw in the picture. The “break” means that do not execute any other case if the value is found. If there is no break, the switch statement will execute every case below the found value.

I will post this so that there will not be two week interval but I promise to update this section with more updates, technicalities, theory among other things.

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