Branching

When an "Algorithm" makes a choice to do one of two (or more things) this is called branching. The most common programming "statement" used to branch is the "IF" statement.

The If Statement

Algorithms in Computer Programs are a lot like recipes, but most recipes don't allow the cook to make choices. If it says, mix two eggs with a cup of flour, that is exactly what you do. But some recipes do allow for variations. Such as, if cooking on the Grill outside, do one thing, if cooking in the oven inside do something else.

In a computer program, the algorithm often must choose to do one of two things depending on the "state" of the program. If the grade is greater than 90, then give the student an A, otherwise if the grade is greater than 80, give the student a B,... etc.

The most used way to make a decision in a program is the "IF" statement. The statement looks like:

Matlab Version

            
    % If Statement in Matlab. Note: "something is true" must be an
    % expression (or variable) that evaluates to (or holds) a true or false
    % boolean value.

    if ( something is true )
      do this code;
      do all code before the end or else;
      do not do anything in the else "block" of code
    else
      % if the something is false (NOTE: we don't have to test this) 
      do other code;
    end
            
          

C, Java, ActionScript Version

            

    // An If statement in Actionscript, Java, or C 

    if ( something is true )
      {
        do this code;
        do all code before the end or else;
        do not do anything in the else "block" of code
      }
    else
      {
        // if the something is false (NOTE: we don't have to test this) 
        do other code;
      }
            
          

The ELSE statement

The else statement shown above is optional... if "NOTHING" is to be done when the condition is false, then the else statement should not be used! For example, below we only congratulate our good students, we do not chastise our bad students.

Matlab Version

            
    grade =  % some_number; 

    if ( grade > 75 )
      fprintf('congrats, your grade %d is passing\n', grade);
    end
            
          

C Version

            
    float grade =  // some_number; 

    if ( grade > 75 )
      {
        printf("congrats, your grade %d is passing\n", grade);
      }
            
          

ActionScript Version

            
    
    // Actionscript Version 

    var grade:Number =  // some_number; 

    if ( grade > 75 )
      {
        trace("congrats, your grade is passing\n");
      }
            
          

The ELSEIF statement

Because we often break problems into several sub paths, Matlab provides an "elseif" control statement. For example, if we have 5 dollars go to the dollar theater, "else if" we have 10 dollars go to the regular theater, "else if" you have 100 dollars, go to a Broadway play, else if you have 1000000 dollars, buy a theater...

The code in Matlab would look like:

Matlab

            
    if (money < 5)
      do this;
    elseif (money < 10)
      do that;
    elseif (money < 1000)
      do a lot of stuff;;
    else
      do a default action when nothing above is true;
    end
            
          

C, Java, ActionScript

            
    if (money < 5)
      {
        do this;
      }
    else if (money < 10)
      {
        do that;
      }
    else if (money < 1000)
      {
        do a lot of stuff;
      }
    else
      {
        do a default action  when nothing above is true;
      }
            
          

Only one of the Paths will be followed when the program is executed! The actual path through the code which is executed is based on which of the if statements is true first, starting from the "Top Down". The first if/else if statement that is true is executed, and all the rest (even if they would be true) are ignored.

Notice how the "else" and the "if" are run together to form "elseif" in Matlab, but are two separate words in C, Java, and ActionScript. Go figure....


The Style of the If statement

There are several "syntaxes" that you should be aware of when using an "if" statement. The are listed below:

  1. The semicolon

    You should never put a semicolon on the same line as the condition for the if statement, nor for the else statement, nor for the end statement.

    Correct:

                
        if ( money < 5 )               
           do this;
        end
                
              

    Incorrect:

        if ( money < 5 );  % WRONG WRONG WRONG
          do this;
        end; % WRONG WRONG WRONG
              
  2. Matching indentation

    When writing an if statement, it is very important to align each else/else if so that they are all indented to the same level. This will make "reading" the code much easier for you and the person who has to maintain your code.

    Here is an example of good indentation of the code and bad indentation:

    Good Indentation/Alignment

                    
        if (money < 5)
          do this;
        else if (money < 10)
          do that;
        else if (money < 1000)
          do a lot of stuff;;
        else
          do a default action  when nothing above is true;
        end
                    
                  

    Bad Indentation

                    
        if (money < 5)
          do this;
          else if (money < 10)
                do that;
        else if (money < 1000)
          do a lot of stuff;;
            else
          do a default action  when nothing above is true;
        end
                    
                  

    Again, proper indentation "shows" helps the programmer (or the reader of the code) to understand the purpose of the code. Think about how in English, we always indent to show a new paragraph. It has a very similar purpose.

  3. IF is not a LOOP

    An "if" statement looks very similar to the "while" loop, but the if statement is not a loop. The code inside the if block (or the else block) will only be executed at most one time. If you want something to happen many times, see loops

  4. The Empty true Branch

    Here is an INCORRECT way to use the ELSE statement, which I will call the "Backwards" else statement.

    Sometimes we will want to do something if the condition is false not true, and you will be tempted to write code with an empty "true" branch and place the code in the "false" branch. Here is a pseudocode example where nothing is done for the "true" condition, a blank exists in the program, and the only code is found in the else part of the if statement.

                
                  if something is true
    
                  else
                      do the code here
                  end
                
              

    This is considered bad programming style and I will give it an :Ugly Alert. Because an if statement represents a true or false condition, we can fix (i.e., remove) the above "empty" block, by "reversing" the condition and removing the else!!!

    Wrong: Matlab

                    
                      % code to do safe division (prevent division by 0)
                      if ( divisor == 0 )
                                                 % blank. (don't do anything if the divsor is zero)
                      else
                          quotient = numerator / divisor;
                      end
                    
                  

    Correct: Matlab

                    
                      % code to do safe division (prevent division by 0)
                      if ( divisor ~= 0 )       % NOT equal (~=) replaces equality (==) 
    
                          quotient = numerator / divisor;
    
                      end
                    
                  

    Wrong: C, Java, ActionScript

                    
                      // code to do safe division (prevent division by 0)
                      if ( divisor == 0 )
                        {
                                                 // blank.  (don't do anything if the divsor is zero)
                        }
                      else
                        {
                          quotient = numerator / divisor;
                        }
                    
                  

    Correct: C, Java, ActionScript

                    
                      // code to do safe division (prevent division by 0)
                      if ( divisor != 0 )       // NOT equal (!=) replaces equality (==) 
                        {
                          quotient = numerator / divisor;
                        }
                    
                  

  5. Shortcuts in Boolean Assignment

    Often we will have code to set assign a boolean value to a variable based on the condition of a loop. Such a statement can be transformed to remove the loop by a direct assignment to the conditional expression. For example:

                
                  if ( money > 10 )
                    go_to_movie = true;
                  else
                    go_to_movie = false;
    
                  // we can modify the above to remove the if and use the short cut:
    
                  go_to_movie = ( money > 10 );
                
              

Back to Topics List