Thursday, September 24, 2015

Decisions and Branching

We must have a way for the program to make a decision, and then execute different code based on the decision. If the number is less than 10, we do one thing, otherwise we do something else. If the object is a rectangle, we obtain the area by multiplying its width by its height; but if the object is a circle, we obtain its area by multiplying its diameter by π.

Indeed, I would venture a guess that the majority of the time, popular computer programs are making decisions. (This is less so for scientific programs that do extensive numerical computations.)



There are several kinds of branching we can do. The simple if statement executes the code inside only if the condition is true. It has the form:

if condition {
   do this stuff
}

The slightly more complication if ... else statement executes one set of code if the condition is true, and it executes a different set of code if the condition is false. It has the form:

if condition {
    do this stuff 
}
else {
    do that other stuff
}

Another option is the chain of if ... else statements. These allow for several conditions, and the code associated with the first matching condition is executed. Here is an example:

if object is a rectangle {
    area = width * height
}
else if object is a circle {
    area = radius * 2 * π
}
else if object is a triangle {
    area = width * height * 0.5
}

Because of the potential for confusion, you should always use curly braces. Most languages allow an if or else clause that has only one internal statement to omit the curly braces. But at least one modern language, Swift, now requires the curly braces even in this minimal case. Other modern languages will probably follow this lead. There are several reasons for adding the curly braces even when they are not strictly required:
  • If someone else adds another line of code later, the code won't break;
  • If there are nested if ... else clauses, the logic will be clearer;
  • In my classes, if you neglect the curly braces, I will mark you down.
You can also make decisions using the switch statement.




No comments:

Post a Comment