01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

306 APPENDIX B The basics of C<br />

anywhere between 0 and 1000 times. You’ll quickly find that you must write a large<br />

amount of duplicative code, and the code is fairly hard to maintain, presenting a lot of<br />

opportunity to introduce errors. It’s also hard to make changes, such as changing the<br />

code to print "Hello, <strong>Objective</strong>-C!" rather than "Hello, World!".<br />

Luckily, C provides a better alternative to such scenarios with a set of statements<br />

that allow you to programmatically loop a specified number of times or while a certain<br />

condition continues to hold true.<br />

The first such statement we investigate is the while loop.<br />

B.4.1<br />

The while statement<br />

The while statement allows you to execute a set of statements as long as a specific condition<br />

continues to hold true. The general form of a while statement is as follows:<br />

while (condition) {<br />

statement block<br />

}<br />

When this statement is executed, the condition is evaluated. If the expression evaluates<br />

to false, execution skips the statements in the block and proceeds to the<br />

first statement after the while loop. If the condition evaluates to true, the statements<br />

in the block are executed before execution returns to the top of the loop,<br />

and the condition is reevaluated to determine if another pass through the loop<br />

should be made.<br />

As an example, the while loop in the following listing causes "Hello, World!" to<br />

be printed 15 times.<br />

Listing B.6<br />

A flexible way to log an arbitrary number of messages<br />

int x = 0;<br />

while (x < 15)<br />

{<br />

NSLog(@"Hello, World!");<br />

x = x + 1;<br />

}<br />

Execution through this loop is controlled by variable x, which is initialized to the<br />

value 0. The while loop condition is evaluated to determine if x is less than 15, which<br />

at this point it is, so the condition initially evaluates to true, and the statements in the<br />

while loop are executed.<br />

Each time through the loop, a call to NSLog is made to emit another copy of the<br />

string "Hello, World!", and the value of x is incremented by 1. Execution then<br />

returns to the top of the while loop, and the loop condition is reevaluated to determine<br />

if another loop through the statement block is required.<br />

After the 15th time through the while loop, the condition x < 15 no longer holds<br />

true, so the looping stops and execution proceeds to the first statement after the<br />

while loop.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!