Seven, conditional statement
1. if statement
if (condition) { code to execute when the condition is true; }
2. if...else statement
if (condition) { code to execute if condition is true; } else { code to execute if condition is false; }
3. if...elseif....else statement
if (condition) { code to execute if condition is true; } elseif (condition) { code to execute if condition is true; } else { code to execute if condition is false; }
4. switch statement
grammar:
switch (expression) { case label1: the code executed when expression = label1; break; case label2: the code executed when expression = label2; break; default: the code executed when the value of the expression is not equal to label1 and label2; }
principle:
- perform an evaluation on an expression (usually a variable)
- compares the value of the expression with the value of the case in the structure
- If there is a match, the code associated with the case is executed
- After the code is executed, the break statement prevents the code from jumping into the next case to continue execution
- The default statement is used if no case is true