The SWITCH statement in C++

In this tutorial from our C++ course, we will learn how to use one more interesting command, the switch statement, also called the switch case statement. Let's see what it is for, how it works, when and how to use it.

Taking different paths - Branches

During our C++ conditional test studies, we learned in practice that the IF and ELSE commands are used to give our codes different directions.

If you type something, one thing happens.
If you type another, something else happens.
And so on. The computer reacts to your commands.


The so-called branches of a program occur.
This was all done with the IF and ELSE conditional tests.
However, there is another possibility of working with branches, which is using the switch statement in C ++.

SWITCH and CASE statements in C++

The switch is a multiple option statement, used to take different actions depending on the value provided. Let's look at the scope of the switch command:
switch (expression)
{
   case value1:
        // code in case expression
        // is equal to value1

   case value2:
        // code in case expression
        // is equal to value2
case value3:
        // code in case expression
        // is equal to value3
   default:
        // code in case expression
        // is not equal to any above
}
It works like this ...
First, the switch will test the expression.
Then it will compare with each case.

If expression equals value1, all code from that case onwards is executed.
If expression equals value2, anything after that case will be executed (the first case will be ignored).
And so on.

If the expression value (which must always be an integer) does not match any case, what is in default is that it will be executed.

Creating a menu with SWITCH statement

Undoubtedly, the main utility of the switch statement is to create menus.
Let's create a simple menu of a banking system.

Let's show some couts with the options:
1. Withdraw
2. Extract
3. Transfer
4. Deposit.


In each case of the switch, we say which option it chose.
If the person enters anything other than this option, it defaults to warning that the option is invalid.

Our code is:
#include <iostream>
using namespace std;

int main()
{
    int op;

    cout << "1. Withdraw" << endl;
    cout << "2. Extract" << endl;
    cout << "3. Transfer" << endl;
    cout << "4. Deposit" << endl;
    cout << "Type an option: ";
    cin >> op;

    switch(op)
    {
        case 1:
            cout << "Selected option: Withdrawl"<<endl;
        case 2:
            cout << "Selected option: Extract"<<endl;
        case 3:
            cout << "Selected option: Transfer"<<endl;
        case 4:
            cout << "Selected option: Deposit"<<endl;
        default:
            cout << "Invalid option"<<endl;
    }


    return 0;
}
Now test ... type 1, for example.
Or 2 ... noticed anything weird? Something wrong?

Look:
Tutorial about switch statement in C++

It wasn't supposed to appear the options below, it's as if you had executed the cases below.
Even the default is always being selected by the switch! This is not how we wanted our program!

Why did this happen?

The BREAK statement in switch case

Note one interesting thing about our definition and explanation of the switch case statement: it executes the case that matches the value to be compared from there. That is, it executes that case in question, and all the others below! Including the default.

So that only the code of each case is executed, just add to the end of each case the following command:

  • break;

See how our code looks now:
#include <iostream>
using namespace std;

int main()
{
    int op;

    cout << "1. Withdraw" << endl;
    cout << "2. Extract" << endl;
    cout << "3. Transfer" << endl;
    cout << "4. Deposit" << endl;
    cout << "Type an option: ";
    cin >> op;

    switch(op)
    {
        case 1:
            cout << "Selected option: Withdrawl"<<endl;
            break;
case 2: cout << "Selected option: Extract"<<endl;
            break;
case 3: cout << "Selected option: Transfer"<<endl;
            break;
case 4: cout << "Selected option: Deposit"<<endl;
            break;
        default: cout << "Invalid option"<<endl; } return 0; }
Now run and see what a cute and cool menu! You select the option, and it executes the correct code, with the correct case!

Usage example: SWITCH CASE

Create a program that receives a numeric value from the user, from 1 to 7, and says what day of the week it is. For example, sunday is 1, monday is 2, tuesday is 3 ... Say that he typed a wrong value too, if he does.

As a curiosity, here's how it would look using IF and ELSE:
#include <iostream>
using namespace std;

int main()
{
    int day;

    cout << "Week day number: ";
    cin >> day;

    if(day==1)
        cout <<"Sunday \n";
    else if(day==2)
        cout <<"Monday \n";
    else if(day==3)
        cout <<"Tuesday \n";
    else if(day==4)
        cout <<"Wednesday \n";
    else if(day==5)
        cout <<"Thursday \n";
    else if(day==6)
        cout <<"Friday \n";
    else if(day==7)
        cout <<"Saturday \n";
    else
        cout <<"Invalid number dayweek \n";

    return 0;
}
See what a horrible, ugly, immoral thing.
Now let's see how this looks pretty and tidy with SWITCH case:
#include <iostream>
using namespace std;

int main()
{
    int day;

    cout << "Dayweek number: ";
    cin >> day;

    switch(day)
    {
        case 1:
            cout <<"Sunday \n";
            break;
        case 2:
            cout <<"Monday \n";
            break;
        case 3:
            cout <<"Tuesday \n";
            break;
        case 4:
            cout <<"Wednesday \n";
            break;
        case 5:
            cout <<"Thursday \n";
            break;
        case 6:
            cout <<"Friday \n";
            break;
        case 7:
            cout <<"Saturday \n";
            break;
        default:
            cout <<"Invalid weekday number";
    }

    return 0;
}
Waaaaay better, don't you think?

Accumulated Cases

A well-known and commonly used technique is to accumulate cases by having the program execute several at once. Let's go to an example:

Write a program using switch case that prompts the user for a letter: A, B, or C, and says which letter was typed. Make sure he wrote both A and a, for example, the same thing.

Guys, as much as you say: type 'B' for the user, some will type 'b' others 'be', the limit of user creativity is infinite, and you have to imagine the bullshit they can do and treat these cases.

See how the solution looks using accumulated cases:
#include <iostream>
using namespace std;

int main()
{
    char let;

    cout << "Type a character: ";
    cin >> let;

    switch(let)
    {
        case 'a':
        case 'A':
            cout <<"You typed A\n";
            break;

        case 'b':
        case 'B':
            cout <<"You typed B\n";
            break;

        case 'c':
        case 'C':
            cout <<"You typed C\n";
            break;

        default:
            cout <<"Invalid letter";
    }

    return 0;
}
Note that if you type 'a', it falls into case 'a' which also executes case 'A', as there is no break there.
That is, that case is selected and go the bottom one.

char is a data type, character. Characters are represented by letters in single quotation marks.
We will learn more about this in the C++ string section.

Cool SWITCH CASE exercise

Using switch case concepts, make a program that asks the user the month (number 1 through 12), and tells you how many days that month has. February has 28 days (not leap year).

In the proposed conditional test exercises tutorial, we will propose and solve this exercise. See the solution there, but not before trying hard enough to solve it.

No comments:

Post a Comment