The three basic building blocks for creating programs are the sequential ordering of code, branches (to make decisions), and loops (to run one or more instructions repetitively). Rather than write one long set of instructions to accomplish a task, a loop lets you write a shorter set of instructions that runs multiple times.
Suppose your program needs to ask for a password from the user before granting access. You could write a bunch of code that keeps checking for a valid password, but this gives you no idea ahead of time how many times someone may try to type in a valid password. With a loop, you just need to write one set of instructions for checking the validity of a password and, if it's valid, granting the user access. The loop can run as many times as necessary, depending on how many times the user tries to type in a valid password. By letting your program respond to uncertainty, loops give your program greater versatility in working in the real world.
All loops run one or more instructions repetitively, but there are two types of loops. One type of loop runs a fixed number of times. In Objective-C, this is called a for
loop. For example, if you want to give users only three chances to type in a valid password, you could create a loop that runs only three times. The moment the user tries to type in a password a fourth time, your program can stop running and simply deny access altogether.
The second type of loop can run zero or more times, depending on circumstances determined by a Boolean expression. In Objective-C, this is called a while
loop. For example, a loop might keep running until the user types in a valid password. That could happen on the first try or the twenty-third try. Since you can't predict ahead of time when a loop should end, you have to let the loop keep running until a certain condition (Boolean expression) is met.
Whereas branches let the computer make decisions, loops let the computer react to uncertainty. When writing Mac programs, you can freely use both types of loops in different parts of your program.
The easiest loop to understand is one that runs a fixed number of times, such as 10 or 20 times. By defining exactly how many times you want a loop to run, you can ensure that the loop always ends eventually.
If a loop never ends, the program can appear to freeze or hang up. Such never-ending loops are called endless loops, and they're the biggest pitfall to avoid when using loops in your program.
To create a loop that runs a fixed number of times, you use a for
statement, which looks like this:
int countingVariable for (initialValue; BooleanExpression; incrementExpression) { instructions; }
A for
statement consists of four items:
The counting variable is defined as an integer before the loop and is used to keep track of how many times the loop has run.
The initial value defines the number that the counting variable is set to when the loop starts. Usually this initial value is 0
or 1
, but it can be any value.
The Boolean expression defines when the loop will run. The loop will stop after the counting variable has reached a certain value, such as 4
. That means the loop might run four times (depending on its initial value).
The increment expression defines how the counting variable changes. Usually the counting variable changes by 1, but you can define this increment change by any number such as 2, 4
, or even a negative number like −3
.
To see how to create a loop using the for
statement, follow these steps:
Open the VariableTest project from the previous chapter.
Click the VariableTestAppDelegate.m
file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.
Modify the code in the VariableTestAppDelegate.m
file as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; for (i = 0; i < 5; i++) { NSLog (@"The value of i = %i", i); } }
Choose File
Click the Build and Run button or choose Build
Quit your program by clicking the Stop button or choosing Product
Choose Run
2010-08-29 13:23:41.515 VariableTest[11731:a0f] The value of i = 0 2010-08-29 13:23:41.519 VariableTest[11731:a0f] The value of i = 1 2010-08-29 13:23:41.521 VariableTest[11731:a0f] The value of i = 2 2010-08-29 13:23:41.521 VariableTest[11731:a0f] The value of i = 3 2010-08-29 13:23:41.522 VariableTest[11731:a0f] The value of i = 4
In this example, the counting variable is i
, the initial value is i = 0
, and the Boolean expression is i < 5
. That means as long as this Boolean expression evaluates to YES
(where i
is a value less than 5
), the loop keeps running. As soon as the Boolean expression i < 5
evaluates to NO
(where the value of i
equals 5
or greater), then the loop stops.
The increment expression is i++
, which is a shortcut for i = i+ 1
. The i++
increment expression simply counts by 1. If you wanted to count by a different value, you could replace the i++
expression with something else such as i = i + 4
.
The for
loop currently runs exactly five times, but you could create a loop that runs five times by using different initial values, Boolean expressions, and increment expressions. For example, this loop also runs five times:
int i; for (i = 105; i > 100; i--) { NSLog (@"The value of i = %i", i); }
If you modify the VariableTest program with this loop, the output looks like this:
2010-08-29 17:31:56.230 VariableTest[12128:a0f] The value of i = 105 2010-08-29 17:31:56.237 VariableTest[12128:a0f] The value of i = 104 2010-08-29 17:31:56.238 VariableTest[12128:a0f] The value of i = 103 2010-08-29 17:31:56.239 VariableTest[12128:a0f] The value of i = 102 2010-08-29 17:31:56.240 VariableTest[12128:a0f] The value of i = 101
In this case, the loop is counting backward from 105 down to 101. The i--
increment expression is equivalent to i = i - 1
.
By changing the initial value, the Boolean expression, and the increment expression, you can define how many times you want the loop to run.
There's another for
loop called fast enumeration, which you'll learn more about in the chapters about arrays (Chapter 8) and dictionaries (Chapter 9). Essentially, fast enumeration lets you scan through a list of data stored in an array or dictionary without having to count at all.
A for
loop always runs a fixed number of times. However, you can stop a for
loop prematurely by using the break
command along with an if
statement inside the for
loop:
int i; for (i = 0; i < 5; i++) { instructions; if (passwordValid) { break; } }
This for
loop might give the user five tries to type in a valid password before blocking access altogether. However, if at any time the user types in a valid password, you want to exit the loop that checks for a valid password and grant access to the user.
To see how the break
command can exit a loop prematurely, follow these steps:
Open the VariableTest project from the previous section
Click the VariableTestAppDelegate.m
file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.
Modify the code in the VariableTestAppDelegate.m
file as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; for (i = 0; i < 5; i++) { NSLog (@"The value of i = %i", i); if (i == 2) { break; } } }
Choose File
Click the Build and Run button or choose Build
Quit your program by clicking the Stop button or choosing Product
Choose Run
2010-08-29 21:07:53.000 VariableTest[12825:a0f] The value of i = 0 2010-08-29 21:07:53.006 VariableTest[12825:a0f] The value of i = 1 2010-08-29 21:07:53.007 VariableTest[12825:a0f] The value of i = 2
Notice that instead of running five times, the loop stopped prematurely (as soon as the value of i
equals 2
) after running only three times.
Instead of prematurely exiting a loop, you can force a for
loop to skip by using the continue
command. Skipping stops the loop from running any remaining instructions in the loop and forces the loop to start over again, but without resetting the counting variable. Like the break
command that prematurely exits a loop, the continue
command also uses an if
statement to determine when to skip or not:
int i; for (i = 0; i < 5; i++) { if (Boolean expression) { continue; } instruction1; }
If the Boolean expression evaluates to YES
, then the computer runs the continue
command and immediately jumps back to the top of the loop without running instruction1
. If you place instructions ahead of the continue
command, those instructions will always run. Any instructions that immediately follow the continue
command will get skipped if the continue
command runs.
To see how the continue
command works to print only even numbers, follow these steps:
Open the VariableTest project from the previous section.
Click the VariableTestAppDelegate.m
file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.
Modify the code in the VariableTestAppDelegate.m
file as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; for (i = 0; i < 5; i++) { if ((i % 2) != 0) { continue; } NSLog (@"The value of i = %i", i);
} }
Choose File
Click the Build and Run button or choose Build
Quit your program by clicking the Stop button or choosing Product
Choose Run
2010-08-29 23:17:25.785 VariableTest[13046:a0f] The value of i = 0 2010-08-29 23:17:25.789 VariableTest[13046:a0f] The value of i = 2 2010-08-29 23:17:25.790 VariableTest[13046:a0f] The value of i = 4
Sometimes you may need a loop to run based on an outside condition that you can't predict ahead of time. Other times you may not want the loop to run even once depending on outside conditions. In both of these cases, you need to choose a different type of loop, either a while
loop or a do-while
loop.
The while
loop can run zero or more times and looks like this:
while (Boolean expression) { instructions; instructions that can change Boolean expression; }
The while
loop repeats one or more instructions and consists of three parts:
A Boolean expression
Instructions to repeat
Instructions that modify the Boolean expression
The Boolean expression determines whether the loop should run. If the Boolean expression evaluates to NO
, it's possible that the while
loop won't run at all.
The second part of the while
loop, the instructions to repeat, can be a single instruction or a group of instructions.
The third, and most important, part of the while
loop are instructions that can change the Boolean expression. If you omit instructions that can change the Boolean expression, the Boolean expression can never change from YES
to NO
, resulting in an endless loop that will hang up or freeze your program, keeping it from working properly.
To see how the while
loop works, follow these steps:
Open the VariableTest project from the previoussection.
Click the VariableTestAppDelegate.m
file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.
Modify the code in the VariableTestAppDelegate.m
file as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; i = 0; while (i < 5) { NSLog (@"The value of i = %i", i); i++; } }
Choose File
Click the Build and Run button or choose Build
Quit your program by clicking the Stop button or choosing Product
Choose Run
2010-08-30 19:41:31.559 VariableTest[14914:a0f] The value of i = 0 2010-08-30 19:41:31.562 VariableTest[14914:a0f] The value of i = 1 2010-08-30 19:41:31.564 VariableTest[14914:a0f] The value of i = 2 2010-08-30 19:41:31.564 VariableTest[14914:a0f] The value of i = 3 2010-08-30 19:41:31.565 VariableTest[14914:a0f] The value of i = 4
The first two lines create an integer variable (i
) and initialize its value to 0
. The Boolean expression is (i < 5)
. Since i
contains 0
, the Boolean expression (i < 5)
evaluates to YES
, causing the while
loop to run.
Inside the while
loop, the NSLog
command simply prints the current value of i
. The other instruction inside the while
loop, i++
, changes the value of the i
variable. This allows the (i < 5)
Boolean expression to evaluate to NO
, causing the while
loop to stop running eventually.
The do-while
loop always runs at least once and looks like this:
do { instructions; instructions that can change Boolean expression; } while (Boolean expression);
Like the while
loop, the do-while
loop also consists of three parts: instructions to repeat, instructions to change the loop's Boolean expression, and the Boolean expression. Since the do-while
loop checks its Boolean expression only after it runs through its instructions, the do-while
loop always runs at least once.
To see how the do-while
loop works, follow these steps:
Open the VariableTest project from the previous section.
Click the VariableTestAppDelegate.m
file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.
Modify the code in the VariableTestAppDelegate.m
file as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; i = 0; do { NSLog (@"The value of i = %i", i); i++; } while (i < 5); }
Choose File
Click the Build and Run button or choose Build
Quit your program by clicking the Stop button or choosing Product
Choose Run
2010-08-30 19:41:31.559 VariableTest[14914:a0f] The value of i = 0 2010-08-30 19:41:31.562 VariableTest[14914:a0f] The value of i = 1 2010-08-30 19:41:31.564 VariableTest[14914:a0f] The value of i = 2 2010-08-30 19:41:31.564 VariableTest[14914:a0f] The value of i = 3 2010-08-30 19:41:31.565 VariableTest[14914:a0f] The value of i = 4
Just as you can exit a for
loop prematurely using the break
command, you can exit a while
or do-while
loop using the break
command. Typically, you use an if-then
statement to determine when to break:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; i = 0; do { NSLog (@"The value of i = %i", i); i++; if (i == 2) {
break; } } while (i < 5); }
This do-while
loop runs twice before exiting as soon as the value of i
equals 2
, printing the following:
2010-08-30 20:12:20.535 VariableTest[15016:a0f] The value of i = 0 2010-08-30 20:12:20.537 VariableTest[15016:a0f] The value of i = 1
You can use the continue
command to cause the while
or do-while
loop to skip over its instructions and return to the beginning. Typically, you use an if
statement to determine when to skip:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; i = 0; do { i++; if ((i % 2) != 0) { continue; } NSLog (@"The value of i = %i", i); } while (i < 5); }
Running this program would print the following:
2010-08-30 20:22:51.675 VariableTest[15138:a0f] The value of i = 2 2010-08-30 20:22:51.683 VariableTest[15138:a0f] The value of i = 4
Loops typically contain one or more instructions arranged sequentially. However, it's possible for a loop to contain instructions organized in a branch or even another loop. When one loop appears inside another loop, that's called a nested loop, an example of which is shown in Figure 7-1.
When one loop is nested inside another one, the inner loop must always finish running first before the outer loop can finish. The inner loop can even change the Boolean expression that the outer loop depends on, but if you try this, make sure that the outer loop eventually ends or you risk creating an endless loop.
It's possible to nest a while
loop inside a for
loop, or vice versa. Although there's no limit to the number of loops you can nest within one another, each nested loop makes understanding how the program works more difficult, which could result in unpredictable behavior if you incorrectly modify any code inside any of the nested loops. Use nested loops only when absolutely necessary to make your programs easier to understand.
To see how nested loops work, follow these steps:
Open the VariableTest project from the previous chapter.
Click the VariableTestAppDelegate.m
file stored inside the Classes folder. The code for that file appears in the middle pane of the Xcode window.
Modify the code in the VariableTestAppDelegate.m
file as follows:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { int i; int j; i = 0; do { NSLog (@"Outer loop %i", i); for (j = 0; j < 3; j++)
{ NSLog (@" Inner loop number %i", j); } i++; } while (i < 3); }
Choose File
Click the Build and Run button or choose Build
Quit your program by clicking the Stop button or choosing Product
Choose Run
2010-08-30 20:50:53.176 VariableTest[15388:a0f] Outer loop 0 2010-08-30 20:50:53.179 VariableTest[15388:a0f] Inner loop number 0 2010-08-30 20:50:53.181 VariableTest[15388:a0f] Inner loop number 1 2010-08-30 20:50:53.182 VariableTest[15388:a0f] Inner loop number 2 2010-08-30 20:50:53.182 VariableTest[15388:a0f] Outer loop 1 2010-08-30 20:50:53.183 VariableTest[15388:a0f] Inner loop number 0 2010-08-30 20:50:53.183 VariableTest[15388:a0f] Inner loop number 1 2010-08-30 20:50:53.184 VariableTest[15388:a0f] Inner loop number 2 2010-08-30 20:50:53.185 VariableTest[15388:a0f] Outer loop 2 2010-08-30 20:50:53.186 VariableTest[15388:a0f] Inner loop number 0 2010-08-30 20:50:53.186 VariableTest[15388:a0f] Inner loop number 1 2010-08-30 20:50:53.187 VariableTest[15388:a0f] Inner loop number 2
Both the inner and outer loops run exactly three times. However, notice that the inner loop repeats multiple times, but the outer loop runs only once.
Loops represent the third basic building block for creating programs, in addition to sequential instructions and branches. Loops run one or more instructions repetitively. The two types of loops you can create are for
and while
loops.
Use the for
loop when you know exactly how many times you want to run a loop. Use a while
loop or do-while
loop when you don't know how many times a loop should repeat, so that your program can adapt to outside circumstances.
If you want a loop to run zero or more times, use the while
loop. If you need the loop to run at least once, then use the do-while
loop. With both the while
loop and do-while
loop, you must change the Boolean expression inside your loop. If you fail to change the loop's Boolean expression, you risk creating an endless loop.
For greater flexibility, you can nest loops inside one another. Since nested loops can be harder to understand, use nested loops sparingly. Just remember that the inner loop must always runs first before the outer loop can finish.
Loops enable your program to run one or more instructions repetitively. Although loops can eliminate the need to write multiple lines of identical (or nearly identical) instructions, loops do make your programs harder to understand. Combining loops with sequential instructions and branches allows you to create virtually any type of program you wish.
18.118.0.42