Introduction to Control Structures: Part 2
Posted on Nov 21, 2011 @ 06:45 AM by ThePhantom
In the last tutorial, we introduced the "if ... else" statements which are one of the most used controlled structures in programming.
In this tutorial we are going to take a look at the switch statement. In general the switch statement consists of three basic elements. The first is the the switch statement itself which takes one argument. This argument is used to determine which option to execute. Then, you have the "case" statement which is used to compare the input argument with your predefined "options" choices. Next you have the break statement which, as it's name indicates, breaks the execution at that point. Last but not least, you have the default statement; this executes whenever the argument does not match any of your "case" statments. The basic syntax is as follow:Notice that the default statement is always at the bottom. This is because as we discussed before, its the statment that executes if no match was found; thus, if its at the beginning it will always execute first. Also if you put a break after the default statement, then the switch will stop there and will not continue to execute other statment after that. On the other hand if you dont put a break after the default statment, it will then execute the default statment plus whatever case that matches with the argument passed.
Also, you can used multiple case statments to execute certain statements. That is, multiple case statments can be used to convey into one result. Let's take a look at the following codeNotice that statement one will execute if variable "equals" is choice1 OR choice2. The is equivalent to usuing an if statement with a disjunction "OR" which is written as " || ". statement1 will execute if variable equals choice1 or if variable equals choice2 (NOT if variable equals choice1 and variable equals choice2). It is a disjunction NOT a conjunction.
switch( variable ) { case "choice1": statements break; case "choice2": statements break; default: statements }
switch( variable ) { case "choice1": case "choice2": statement1 break; case "choice3": statement2 break; case "choice4": statement3 break; default: default_statement }
Comments: