The basics of programming in c++ for beginners

The switch statement in the C++

оператор switch, switch c++, switch в с++, оператор множественного выбора, свич с++, основы программированияIn this article, we slightly modify the format of the study topics. At the beginning, let's look at an example with statement switch(switch), which will be a lot of comments about how, that occurs in the code. A whole theory will be located below.

The work of the statement of multiple choiceswitch in C ++, we consider in addressing this problem: Let's, the user has a numbered list of the metro stations in Barcelona. You must write code, wherein the dialogue with the user is implemented, namely, asked to enter room underground station. After entering the Station Number, we have to show it on the screen and the name of the travel time. If, however, with the number of stations is not, inform and propose to enter the number again. Begin:

To string 13 – everything is clear: Ads necessary variables, conclusions Questions on the screen, and entry into the loop do while. In string 14 we got valueanswer, which introduces the user. Then look, how interesting works switch() : in parentheses pass him answer (string 16) and next to each wordcase  write possible valuesanswer, the user can enter (1, 2, 3 …).

after each case you see the statement : , he required. It is followed by the command, that must be met, if the valuecase coincides with the value of answer. Statementbreak  at the end of each block case  It is also required. It indicates to the compiler, if this case It was performed, you have to get out of switch().  That is actually, when performed switch () begins search and search for the desired case.

Ifanswer  equal to 1, work case 1 and the screen will show the, that it is registered to a keywordbreak, and all other case, будут проигнорированы. Если answer equal to 2 – executed onlycase 2 and exited switch(). What if no value blocks case does not match, with the value, that took switch() (in our case answer)? For this purpose the blockdefault. Before him it comes, just then, when none of case not worked and, respectively, not fulfilled nonebreak  these units.

In our example,, it will work if the value, which will bring the user, will be <1 or >5. Then the user will see on the screen a message that, that with such a number of subway stations, and there is no need to re-enter.

In the loop, we always check the valueanswer, which is entered by the user. This is done using if . If the value is within a suitable range, we (from 1 to 5 ), the manipulated variable var It will be set 0. In this case, the user will no longer be prompted to enter a new value.

Here's how the program works:

оператор switch, switch c++, switch в с++, оператор множественного выбора, свич с++

 What you should remember:

  • syntax:

оператор switch, switch c++, switch в с++, оператор множественного выбора, свич с++

    • blockdefault  It can be positioned anywhere in the blockswitch()  For example the first and second case . His code in any event will run only, if you find the value in the blocks case. But, I suggest you have it at the end, as do most programmers. It is an unwritten rule.
    • a lower block switch(), whetherdefault or case, operator break  You can not specify. This is done in this example. But we should remember, that in all other break mandatory!
    • default  It is optional. His in switch()  may not be at all. In this case, If no value blocks case  does not coincide with the, that took switch() , the program moves to the next line of code, located under the switch()
  • sometimes blocks case  check character, instead of numerical values. Then you must take these characters in single quotes –  case ‘b’: ,  case ‘G’: ,  case ‘+’ etc.

Anyone who has a desire to – see video tutorial on the topic.

Still have questions – ask them in the comments. Be sure to answer all.   Learn the basics of programming with us! More examples usingswitch  in C ++ discussed in the article Tasks:  The switch statement in the C++.

49 thoughts on “The switch statement in the C++

  1. #include
    #include
    using namespace std;
    int main()
    {
    setlocale(LC_ALL, “RU”);
    int answer;
    cout << "\a \a\a";
    cout << " \t How are user?" <> answer;
    switch (answer)
    {
    case (“fine”):
    case (“well”) :
    case (“Good”) :
    case (“Fine”) :
    case (“excellent”) :
    case(“Otilichno”) :
    break;
    cout << "Ок тогда начинаем" << endl;
    case ("не очень"):
    case ( "плохо:пойдет") :
    case ("не спрашивай") :
    case ( "Не очень" ):
    case ("Плохо пойдет" ):
    case ( "Не спрашивай") :

    cout << "Ок тогда в другой раз заходи" << endl;
    break;
    default:
    cout << "Пожалуйста граматно пиши" << endl;
    }

    system("pause");
    return 0;
    }
    somebody help me

  2. This lesson is in the thread “Loops and branching statements” under number 3. This program uses do and while statements which are only covered in #6. In short, I'd rather swap them or something., I haven't looked further, but I don't understand how these operators work in this program.

  3. help me please, I'm a beginner.

    float AddVat(float price, int category)
    float total_price=0;

    The goal is for the function to calculate and return the total cost including tax (not allowed to use scanf, switch only)

    taxes:
    1 category 20%
    2- 20%
    3-20%
    4-15%
    5-8%
    6-0%

  4. It is not clear how case: checks the value of the variable int answer = 0 replacing it

  5. Why do do while here????
    It works without it, and cin can be placed behind the loop and everything will work the same

Leave a Reply

Your email address will not be published. Required fields are marked *