Changes

Jump to: navigation, search

Objective-C Looping - The for Statement

1,522 bytes added, 13:33, 13 October 2009
Continuing for Loops
6
8
</pre>
 
== for Loops with Multiple Variables ==
 
In the examples we have covered so far we have used a single variable within the ''for'' loop construct. Objective-C actually permits multiple variables to be modified within the looping process. In the following example, the for loop increments two variables, i and j
 
<pre>
int j;
int i;
 
for (j = 0, i = 0; i < 10; i++, j++)
{
NSLog( @"i = %i, j = %i", i, j);
}
</pre>
 
Note that although both ''i'' and ''j'' are initialized and incremented in this loop, the number of times the loop is to be performed is still based on the value of ''i'' through the ''i > 10'' expression. The initialization and modification expressions for additional variables do not need to be the same as the control variable. For example, the following example initializes ''j'' to 5 multiplies it by 2:
 
<pre>
int j;
int i;
 
for (j = 1, i = 0; i < 10; i++, j *= 2)
{
NSLog( @"i = %i, j = %i", i, j);
}
</pre>
 
When the above loop is executed we get output similar to:
 
<pre>
2009-10-13 09:32:22.498 t[1867:10b] i = 0, j = 1
2009-10-13 09:32:22.500 t[1867:10b] i = 1, j = 2
2009-10-13 09:32:22.500 t[1867:10b] i = 2, j = 4
2009-10-13 09:32:22.501 t[1867:10b] i = 3, j = 8
2009-10-13 09:32:22.501 t[1867:10b] i = 4, j = 16
2009-10-13 09:32:22.502 t[1867:10b] i = 5, j = 32
2009-10-13 09:32:22.502 t[1867:10b] i = 6, j = 64
2009-10-13 09:32:22.503 t[1867:10b] i = 7, j = 128
2009-10-13 09:32:22.503 t[1867:10b] i = 8, j = 256
2009-10-13 09:32:22.503 t[1867:10b] i = 9, j = 512
</pre>

Navigation menu