## Tuesday, October 13, 2009

### Objective-C Tuesdays: for loop variations

Last week, we examined the structure of the `for` loop. Today we will look at some `for` loop idioms.

Infinite loop If you omit the initialization, condition and action expressions, you get an infinite loop:
```for (;;) {
NSLog(@":-)");
}```

Missing loop expression Sometimes, there's no need to initialize a variable before looping, so the initialization expression is omitted:
```char *process_line(char *buffer) {
for ( ; *buffer != '\n'; buffer++) {
/* do something with characters */
}
return buffer;
}```
Similarly the condition or action expressions are sometimes omitted.

Nested loops When building or processing tables of information, put one `for` loop inside another:
```for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
NSLog(@"%d X %d = %d", i, j, i * j);
}
}```

Parallel iteration You can use multiple loop counter variables by using the comma (`,`) operator to squeeze multiple expressions into initialization and action:
```int i, j;
for (i = 0, j = 9; i < 10; i++, j--) {
destination[i] = source[j];
}```

There's a gotcha with the initialization expression however: only one loop counter variable can be declared there. It seems logical to do this:
`for (int i = 0, int j = 9; i < 10; i++, j--) ...`
but unfortunately you can only do this:
```int j;
for (int i = 0, j = 9; i < 10; i++, j--) ...```

Next week, we'll look at the Objective-C 2.0 `for...in` loop.
{"ft_lang_label":"__label__en","ft_lang_prob":0.7131918,"math_prob":0.9299408,"size":1429,"snap":"2022-40-2023-06","text_gpt3_token_len":376,"char_repetition_ratio":0.12,"word_repetition_ratio":0.069767445,"special_character_ratio":0.31280616,"punctuation_ratio":0.21070234,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9686617,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-02-08T01:03:11Z\",\"WARC-Record-ID\":\"<urn:uuid:e1f17706-38fe-4d95-9001-dac03b0389d1>\",\"Content-Length\":\"58464\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e8032b4b-8004-4e98-9875-54fd1c209438>\",\"WARC-Concurrent-To\":\"<urn:uuid:86e19b7f-ac65-449a-83cf-31c2cf20d3b6>\",\"WARC-IP-Address\":\"142.251.111.121\",\"WARC-Target-URI\":\"http://blog.ablepear.com/2009/10/objective-c-tuesdays-for-loop_13.html\",\"WARC-Payload-Digest\":\"sha1:QOXAIK4WMFGMTSJJGYRHE7H6JTFEFGBW\",\"WARC-Block-Digest\":\"sha1:22MTA67JTYREMOMPBCTW2IJVW5E4VWKB\",\"WARC-Identified-Payload-Type\":\"application/xhtml+xml\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764500664.85_warc_CC-MAIN-20230207233330-20230208023330-00624.warc.gz\"}"}