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:
  1. switch( variable ) {
  3. case "choice1":
  4. statements
  5. break;
  7. case "choice2":
  8. statements
  9. break;
  11. default:
  12. statements
  14. }
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 code
  1. switch( variable ) {
  3. case "choice1":
  4. case "choice2":
  5. statement1
  6. break;
  8. case "choice3":
  9. statement2
  10. break;
  12. case "choice4":
  13. statement3
  14. break;
  16. default:
  17. default_statement
  19. }
Notice 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.