Introduction to Control Structures: Part 1

Posted on Mar 02, 2011 @ 04:04 AM by ThePhantom

Programming languages by default execute in sequence; that is they execute line by line. This is very useful since you want to have an order; but how about if we need to make decisions and evaluate some input and decide which path to take depending on that input. Well, that’s when we use Control Structures. Control Structures allow us, programmers, to change that default sequential execution. In most Programming Languages such as PHP, C++, C, C#, Java, JavaScript, and others, we have Control Structures. The first Control Structure we are going to talk about is the “if” and “if … else”. What this structure does is to evaluate the condition of the “if” statement and determine if it’s true or false; then if it’s true executes the statements inside the “if” body, otherwise executes statements in the else body or continues executing the rest of the program. The syntax is similar in different programming languages; although it might change a bit. The general syntax is as follow:
  1. if( condition )
  2. statement
  5. if ( condition )
  6. statement
  7. else
  8. statement
NOTICE that we did not use the curly braces “{}” in any of the “if … else” statements. This is because there is no need to use the braces if there is only one statement in the body of the “if .. else” statement; but it is a good programming practice to always put the braces, even though if there is only one statement inside the body if the “if … else” statements. NOTE: the else statement must be always associated with an if statement, that is it must be immediately after the if statement. These condition statements can be nested. That is to put one inside the other one. For instance
  1. if ( condition )
  2. statement
  3. else
  4. if ( condition1 )
  5. statement
  6. else
  7. statement
These nested control structures can be rewritten using “else if”. For example, the above code can be rewritten as:
  1. if( condition )
  2. statement
  3. else if ( condition1 )
  4. statement
  5. else
  6. statement
Let’s take a look at the following code
  1. // Section 1
  2. if( condition )
  3. statement
  4. else if ( condition1 )
  5. statement
  6. else if ( condition2 )
  7. statement
  8. else if ( condition3 )
  9. statement
  11. // Section 2
  12. if( condition )
  13. statement
  14. if ( condition1 )
  15. statement
  16. if ( condition2 )
  17. statement
  18. if ( condition3 )
  19. statement
In the previous code both sections will accomplish the same task but with the only difference that Section 1 will do it faster and more efficiently than Section 2. That is because when a condition in Section 1 is evaluated to true then the program doesn’t evaluate the rest of the conditions; whereas in Section 2 when one condition is evaluated to true the program will keep evaluating the remaining conditions.