Chapter 6. Making Decisions with Branches

The simplest programs consist of one or more instructions or lines of code that the computer follows sequentially, one after another. While such sequential ordering forms the basis for programming, programs need greater flexibility to make decisions depending on the current situation.

A branch provides the computer with a choice of two or more different sets of instructions to follow. The simplest type of branch provides two choices, but there's no theoretical limit to the number of branches a program can have. A complicated program may need to make hundreds or even thousands of possible decisions.

Computers decide which choice, or branch, to follow based entirely on a certain condition, known as a Boolean condition or expression. In real life, people use Boolean expressions all the time to make decisions.

Suppose you want to find something to eat. If you're in a hurry, you might go to a fast-food restaurant. If want a nicer meal, you might look for a sit-down restaurant. In each case, your decision depends on a Boolean condition.

In the first example, the Boolean expression is whether you're in a hurry or not, which can evaluate to either YES or NO. In the second example, the Boolean expression is whether you want a nicer meal. To make decisions, computers need to evaluate a Boolean expression, which determines which branch of instructions to follow.

A typical branch in a video game might ask the user, "Continue playing?" Based on the response (a Boolean expression that evaluates to YES or NO), one branch might run the game over again while the second branch might end the game right away.

Branches and the sequential ordering of code represent two of the three basic building blocks to creating programs. (The third building block is a loop, which you'll learn more about in Chapter 7.) Normally a branch contains one or more instructions arranged sequentially, but a branch can contain other branches, as shown in Figure 6-1.

Branches can contain other branches.

Figure 6-1. Branches can contain other branches.

Understanding Boolean Expressions

When making a decision, a person needs to examine a condition. For example, if it's raining, they might take an umbrella or wear a raincoat. In this case, the condition is whether it's raining or not. If so, take an umbrella or raincoat. If not, then don't take either one.

Computers also need to examine conditions to decide which branch of instructions to follow. Such conditions always represent a True or False value, which are called Boolean conditions, after Boolean logic.

In the Boolean condition of whether it's raining or not, the Boolean value is either True or False. If it's True, that means it is raining. If it's False, that means it is not raining.

To represent the values of True and False, programming languages treat the value of True as 1 and the value of False as 0. In Objective-C, True values are represented as YES and False values are represented as NO.

The simplest Boolean condition in Objective-C is simply a YES or NO:

if (YES)
{
    NSLog (@ "Hello, world!");
}

In the preceding example, the code simply prints "Hello, world!" because the condition is always YES. This code is equivalent to the following:

NSLog (@ "Hello, world!");

A Boolean value of YES or NO is often assigned to a variable:

BOOL Flag = YES;

This code simply declares a Boolean variable, called Flag, and assigns it a value of YES. Rather than assign a value, you could have just declared a Boolean variable and left its value unknown:

BOOL Flag;

Before you could use such a Boolean variable, you would have to assign it a value of YES or NO. While you can assign a value of YES or NO, it's far more common to evaluate a condition to determine its Boolean value. For example, to determine whether or not to take an umbrella or raincoat, the Boolean condition might be as follows:

if (raining outside)
{
  take umbrella or raincoat;
}

Depending on whether or not it's raining, this Boolean condition evaluates to either YES or NO. In programming, the Boolean conditions are usually comparisons between two different values. This comparison of values is known as an expression, an example of which follows:

45 > 10

Since 45 is always greater than 10, this Boolean expression always evaluates to YES. Obviously, this is no different from simply replacing the entire 45 > 10 expression with YES. To make such Boolean expressions more useful, it's more common to replace one or more fixed values with a variable. Since the value of a variable can change, this causes the Boolean expression to vary as well.

For example, consider this Boolean expression:

X > 10

Depending on the actual value of X, this Boolean expression evaluates to either YES or NO. If the value of X is 11 or greater, then this Boolean expression evaluates to YES. If the value of X is 10 or less, it evaluates to NO.

A Boolean expression can even compare two different variables:

X > Y

This Boolean expression varies depending on the actual values stored in the X and Y variables.

A Boolean expression can even compare mathematical calculations:

X + 15 > Y - 47

There's actually no limit to the number of variables you can use in a Boolean expression. No matter how many variables are used, the Boolean expression always evaluates to either YES or NO. For example, the following expression would evaluate to YES or NO depending on the values of the four variables:

X + 15 + Z > Y - 47 + W

Boolean Comparison Operators

A Boolean expression compares two values to determine a YES or NO value. To compare two values, you have to use a Boolean comparison operator. Table 6-1 lists the various Boolean comparison operators.

Table 6-1. Boolean Comparison Operators

Boolean Operator

Meaning

==

Equal

!=

Not equal

>

Greater than

>=

Greater than or equal

<

Less than

<=

Less than or equal

Note

Unlike some programming languages, to compare whether two values are equal in Objective-C, you have to use double equal signs. If you use a single equal sign, the computer will think you're assigning a value to a variable, such as X = 18. Forgetting this second equal sign is a common error when writing a Boolean expression to compare whether two values are equal.

Assuming that the value of X is 28, Tables 6-2 shows how the computer would evaluate the various Boolean expressions.

Table 6-2. Evaluating Boolean Expressions

Boolean Expression

Evaluates To

X == 45

NO

X != 45

YES

X > 45

NO

X >= 45

NO

X < 45

YES

X <= 45

YES

On each side of a Boolean comparison operator, you can have any of the following:

  • A value, such as 128 > 344

  • A variable that can represent different values, such as X > 344 or 128 > Y

  • A mathematical expression with a variable, such as X + 23 > 344

Suppose you had a Boolean expression as follows:

X = 36;
if (X < 98)
{
  NSLog (@"Hello, world!");
}

The first step that the computer would take is to substitute the value of X into the (X < 98) Boolean expression like this:

if (36 < 98)
{
  NSLog (@"Hello, world!");
}

The Boolean expression (36 < 98) evaluates to YES, so the next step would look like this:

if (YES)
{
  NSLog (@"Hello, world!");
}

This code just boils down to this:

NSLog (@"Hello, world!");

Boolean Logical Operators

Just as mathematical operators let you calculate new values with numbers, Boolean logical operators let you calculate new values using Boolean expressions. Boolean logical operators are useful to evaluate two Boolean expressions.

The following are the four types of Boolean logical operators:

  • && (And)

  • || (Or)

  • ^ (Xor)

  • ! (Not)

The ! (Not) Operator

The !(Not) operator is the simplest Boolean logical operator to understand since it simply reverses the value of a Boolean expression. For example:

!(YES) = NO
!(NO) = YES

Assume the value of X is 57 in the following Boolean expression:

!(X == 86)

First, the computer would substitute X with 57 in the Boolean expression as follows:

!(57 == 86)

Now the computer evaluates this Boolean expression to NO:

!(NO)

The ! operator reverses the Boolean value so that the entire Boolean expression evaluates to the following:

!(NO) = YES

The ! operator may look puzzling as to its purpose, but consider a program that verifies whether the user typed in a valid password. The loop might look like this:

while !(validPassword)
{
  Ask for password;
}

This code tells the computer that as long as the password is not valid, it should keep asking for a password.

The && (And) Operator

Sometimes you may need to combine two Boolean expressions to create a single Boolean value. For example, suppose you wanted to decide whether to take an umbrella. First, you might check if it's raining. Then you might check if you need to go out. If both of these Boolean conditions are YES, then you would take an umbrella. Writing this out like code might look like this:

if (raining outside) && (need to go outside)
{
  take umbrella;
}

If the Boolean expression (raining outside) is NO, then you won't need to take an umbrella regardless of whether you need to go outside or not. Likewise, if the Boolean expression (need to go outside) is NO, then it doesn't matter if it's raining or not since you won't need an umbrella.

The && operator takes two Boolean values and calculates a new result, as shown in Table 6-3.

Table 6-3. The && (And) Operator Table

$$

NO

YES

NO

NO && NO = NO

NO && YES = NO

YES

YES && NO = NO

YES && YES = YES

When calculating a new result with the && operator, the Boolean expression represents YES only if both conditions represent YES. If either condition is NO, then the entire Boolean operation is also NO.

The || (Or) Operator

Another way to combine two Boolean expressions to create a single Boolean value is through the || (Or) operator. The || operator takes two Boolean values and calculates a new result, as shown in Table 6-4.

Table 6-4. The || (Or) Operator Table

||

NO

YES

NO

NO || NO = NO

NO || YES = YES

YES

YES || NO = YES

YES || YES = YES

When calculating a new result with the || operator, the Boolean expression represents YES if either one (or both) of the conditions also represents YES. If both conditions are NO, then the entire Boolean operation is NO.

For example, suppose you wanted to decide whether to wear boots. First, you might check if it's raining. Second, you might check if it's snowing. If either of these Boolean conditions is YES, then you would wear boots. Writing this out as code might look like this:

if (raining outside) || (snowing outside)
{
  wear boots;
}

You need to wear boots if (raining outside) is YES or (snowing outside) is YES. The only time the entire Boolean expression does not evaluate to YES is when both Boolean conditions evaluate to NO.

The ^ (Xor) Operator

Yet another way to combine two Boolean expressions to create a single Boolean value is through the ^ (Xor) operator. The ^ operator (also called an exclusive Or) takes two Boolean values and calculates a new result, as shown in Table 6-5.

Table 6-5. The ^ (Xor) Operator Table

^

NO

YES

NO

NO ^ NO = NO

NO ^ YES = YES

YES

YES ^ NO = YES

YES ^ YES = NO

With the ^ operator, two Boolean expressions evaluate to NO when both are identical (both NO or both YES). If the two Boolean expressions are different, then they always evaluate to YES.

Note

The Xor operator is often used in encryption. One of the simplest encryption algorithms is called the XOR cipher.

Once you understand Boolean expressions, including both comparison and logical operators, you'll be ready to use Boolean expressions in branches and loops when writing your own programs.

Branches

A branch defines two or more possible sets of instructions (code) for the computer to follow, based on a Boolean expression that evaluates to YES or NO. In Objective-C, the two most common types of branches are the if and switch statements.

An if statement lets you choose between two or more alternative sets of instructions to follow. A switch statement behaves exactly like an if statement, but it's simpler to write when you need to provide a large number of alternative sets of instructions.

The Simplest if Statement

The if statement gets its name because it checks a single Boolean expression. If this Boolean expression is YES, then the if statement follows one or more instructions. If this Boolean expression is NO, then it doesn't do anything.

The simplest if statement lets you run exactly one instruction based on a Boolean expression. In Objective-C, this simple if statement looks like this:

if (Boolean expression) instruction;

To see how to use this simple if statement, modify the VariableTest project from Chapter 5 by following these steps:

  1. Open the VariableTest project from the previous chapter.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        BOOL Flag = YES;
        if (Flag) NSLog (@"It works!");
      }
  4. Choose File

    The Simplest if Statement
  5. Click the Build and Run button or choose Build

    The Simplest if Statement
  6. Quit your program by clicking the Stop button or choosing Product

    The Simplest if Statement
  7. Choose Run

    The Simplest if Statement
    2010-08-28 14:51:51.162 VariableTest[9492:a0f] It works!

Following Multiple Instructions in an if Statement

The simplest if statement lets you run only one instruction if a Boolean expression is YES. In most cases, you'll need to run two or more instructions if a Boolean expression is YES. To do this, you need to use curly brackets around the instructions you want to run:

if (Boolean expression) {
    instruction1;
    instruction2;
}

To make the curly brackets more visible, you could just place the beginning, left curly bracket on a separate line:

if (Boolean expression)
{
    instruction1;
    instruction2;
}

In either case, using curly brackets lets you run two or more instructions if a Boolean expression is YES.

The if-else Statement

The if statement runs one or more instructions if a Boolean expression is YES. However, if the Boolean expression is NO, then the if statement doesn't run any instructions. There may be times when you want the computer to follow one set of instructions if a Boolean expression is YES, but follow another set of instructions if the Boolean expression is NO. In such cases, you have two choices.

First, you can create two separate if statements:

if (Boolean expression == YES)
{
    instruction1;
    instruction2;
}
if (Boolean expression == NO)
{
    instructionA;
    instructionB;
}

No matter what the Boolean expression may be (either YES or NO), the instructions in one of these if statements will run. Of course, writing two separate if statements can be clumsy, so Objective-C offers an if-else statement that lets you define two sets of instructions to follow:

if (Boolean expression == YES)
{
    instruction1;
    instruction2;
}
else
{
    instructionA;
    instructionB;
}

This single if-else statement makes much clearer which set of instructions the computer will follow depending on the value of the Boolean expression. If it's YES, then the computer follows the first set of instructions. If it's NO, then the computer follows the second set of instructions.

The if-else if Statement

The if-else statement runs either one set of instructions or a second set of instructions. If the computer does not follow the first set of instructions, it always follows the second set of instructions.

However, you may not want the computer to run a second set of instructions automatically. Instead, you may want to evaluate a second Boolean expression before running the second set of instructions. Such an if-else if statement looks like this:

if (Boolean expression 1 == YES)
{
instruction1;
    instruction2;
}
else if (Boolean expression 2 == YES)
{
    instructionA;
    instructionB;
}

Although it's similar to the ordinary if-else statement, the if-else if statement works a lot differently. If Boolean expression 1 is YES, then the computer runs only the first set of instructions (instruction1 and instruction2). If Boolean expression 1 is NO, then the computer evaluates Boolean expression 2.

If Boolean expression 2 is YES, then the computer follows the second set of instructions (instructionA and instructionB). However, if Boolean expression 2 is NO, then the computer winds up not following any of the instructions.

The preceding if-else if statement could be rewritten as follows:

if (Boolean expression 1 == YES)
{
    instruction1;
    instruction2;
}

if (Boolean expression 1 == NO) && (Boolean expression 2 == YES)
{
    instructionA;
    instructionB;
}

For the computer to follow the second set of instructions (instructionA and instructionB), two conditions must be met. First, Boolean expression 1 must be NO. Second, Boolean expression 2 must be YES.

In addition to letting you evaluate a Boolean expression before running each set of instructions, another advantage of the if-else if statement is that it lets you choose from two or more sets of instructions, such as in this example:

if (Boolean expression 1 == YES)
{
    instruction1;
    instruction2;
}
else if (Boolean expression 2 == YES)
{
    instructionA;
    instructionB;
}
else if (Boolean expression 3 == YES)
{    instructions3;
    instructions4;
}
else if (Boolean expression 4 == YES)
{
instructionsC;
    instructionsD;
}

Unfortunately, the more alternative sets of instructions you include in the if-else if statement, the messier your code gets and the harder it is to read. If you need to check a Boolean expression before running multiple alternative instructions, it's simpler to use a switch statement.

The switch Statement

The switch statement is often used to provide a large number of alternative instructions for the computer to follow. The main difference is that a switch statement tries to match a variable to a constant value. For example, consider thesetwo if statements:

if (X == 45)
{
    instruction1;
    instruction2;
}

if (X == 97)
{
    instructionA;
    instructionB;
}

The equivalent switch statement might look like this:

switch (X)
{
    case 45:
       instruction1;
       instruction2;
       break;

    case 97:
       instructionA;
       instructionB;
       break;
}

Rather than just evaluate a YES or NO value, the switch statement takes a value and tries to match it. If the value matches to a specific value, then the computer runs that set of instructions:

switch (expression)
{
    case match1:
       instruction1;
       instruction2;
       break;

   case match2:
       instruction3;
       instruction4;
break;

   case match3:
       instruction5;
       instruction6;
       break;

   default:
       instructionA;
       instructionB;
       break;
}

This switch statement is equivalent to the following if statements:

if (expression == match1)
{
   instruction1;
   instruction2;
}

if (expression == match2)
{
   instruction3;
   instruction4;
}

if (expression == match3)
{
   instruction5;
   instruction6;
}
else
{
   instructionA;
   instructionB;
}

The switch statement is somewhat unusual for two reasons. First, you do not use curly brackets to enclose multiple lines of code inside the switch statement. Second, at the end of each set of instructions, you need to use a break command.

The break command simply tells the computer to stop following instructions. Without this break command, the computer would simply keep following instructions stored in another part of the switch statement. For example, consider the following switch statement where the break command is missing:

switch (expression)
{
    case match1:
       instruction1;
       instruction2;

  default:
       instructionA;
       instructionB;
       break;
}

This is actually equivalent to the following, which is probably not what you want:

switch (expression)
{
    case match1:
       instruction1;
       instruction2;
       instructionA;
       instructionB;
       break;

  default:
       instructionA;
       instructionB;
       break;
}

The case and break commands define the beginning and the end of a group of instructions. If you omit the break command, the computer will get confused and run additional instructions that you didn't intend.

Note

Omitting a break command is the number one cause of errors when using the switch statement.

By purposely omitting the break command, you can match multiple values to the same set of instructions:

switch (expression)
{
    case match1:
    case match2:
       instruction1;
       instruction2;
       break;

  default:
       instructionA;
       instructionB;
       break;
}

The preceding switch statement is equivalent to the following:

if (expression == match1)  || (expression == match2)
{
      instruction1;
      instruction2;
}
else
{
     instructionA;
     instructionB;
}

To see how to use a simple switch statement, modify the VariableTest project from the section "The Simplest if Statement," earlier in this chapter, by following these steps:

  1. Open the VariableTest project.

  2. Click the VariableTestAppDelegate.m file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.

  3. Modify the code in the VariableTestAppDelegate.m file as follows:

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        int X = 2;
        switch (X)
        {
            case 1:
                NSLog (@"X = 1");
                break;
            case 2:
                NSLog (@"X = 2");
                break;
            default:
                NSLog (@"Default code");
                break;
        }
    }
  4. Choose File

    The switch Statement
  5. Click the Build and Run button or choose Build

    The switch Statement
  6. Quit your program by clicking the Stop button or choosing Product

    The switch Statement
  7. Choose Run

    The switch Statement
    2010-08-28 17:59:32.654 VariableTest[9921:a0f] X = 2

Go back and change the first line in the applicationDidFinishLoading method to the following:

int X = 1;

Now if you run this program and view the log window, you'll see this:

2010-08-28 17:59:32.654 VariableTest[9921:a0f] X = 1

Go back and change the first line one more time, to the following:

int X = 99;

Now if you run this program and view the log window, you'll see this:

2010-08-28 17:59:32.654 VariableTest[9921:a0f] Default code

By examining the switch statement, you can see exactly how it behaves based on the value that you give it for X.

Summary

To make decisions, computers rely on Boolean expressions that represent a YES or NO value. The simplest Boolean expressions are YES or NO values, but more complex Boolean expressions rely on comparison operators and logical operators.

Comparison operators compare two values to determine a YES or NO value. The six types of comparison operators include == (equal), != (not equal), > (greater than), >= (greater than or equal to), < (less than), and <= (less than or equal to).

Logical operators change the value of a Boolean expression somehow. The four types of logical operators are ! (Not), && (And), || (Or), and ^ (Xor).

Boolean expressions are always used in branching statements to determine which set of instructions to follow. The simplest type of branching statement is an if statement that runs exactly one instruction if a Boolean expression is YES.

Since running a single instruction is limited, most if statements can run one or more instructions, enclosed by curly brackets.

For greater flexibility, you can also use an if-else statement, which provides two sets of instructions for the branching statement to choose from. For even greater flexibility, there's also an if-else if statement, which lets the computer evaluate a Boolean expression before running any set of instructions.

The if-else if statement can let you create an unlimited number of alternative sets of instructions to follow, but to make these branches easier to understand, you can often replace the if-else if statement with a switch statement. The switch statement examines a variable and compares that variable to fixed values to determine which set of instructions to follow.

Branching statements give your program the power to react to the user and outside data. As a result, branching statements represent one of the three main building blocks (the other two being loops and the sequential ordering of instructions) for creating any program.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.81.153