The switch structure in C++ can also implement a variety of branch structures, similar to the else if structure. That is, for various situations, the program can judge which branch to choose based on conditions, which enriches the possibilities of the program. The usage method is similar to the C language. The general structure is as follows:
switch(expression){case constant expression 1: statement 1; case constant expression 2: statement 2; case constant expression 3: statement 3; //... case constant expression n: statement n; default: statement n +1;}Note that there is no semicolon after the switch bracket! This is an easy mistake for newbies.
The execution flow of the program is to first execute the value of the expression in parentheses after the switch, and then compare it with the constant after the case to see which one is equal. Once equal, execution starts from the statement after the colon of the case, that is, the corresponding statement is executed. After the statement, the subsequent case statement is also executed, and no longer determines whether the case values are equal or not. And if after comparison it is found that all cases are not equal, then the statement after default will be executed. This is the execution characteristic of the switch structure.
Let's take an actual problem as an example to explain the usage in detail. Question 1783 is the day of the week judgment machine. Please read the question by yourself first and try to solve and submit it, and then refer to the answer.
The reference answer is as follows:
#include<iostream>usingnamespacestd;intmain(){intn;cin>>n;switch(n){case0:cout<<Sunday;break;case1:cout<<Monday;break;case2:cout<<Tuesday;break; case3:cout<<Wednesday;break;case4:cout<<Thursday;break;case5:cout<<Friday;break;case6:cout<<Saturday;break;default:cout<<inputerror!;}return0;}Please use the computer to code in person, and remember not to be too conceited!