Objective C Tutorial - Objective C for loop






A for loop executes a sequence of statements multiple times with a loop variable.

Syntax

The syntax of a for loop in Objective-C programming language is:

for ( init; condition; increment )
{
   statement(s);
}
  • init is executed first, and only once. We can declare and initialize loop control variables here.
  • Then condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow control jumps to the next statement just after the for loop.
  • After the body of the for loop executes each time, increment statement is execusted. We can update loop control variables here.




Example

#import <Foundation/Foundation.h>
 
int main ()
{
   /* for loop execution */
   int a;
   for( a = 10; a < 20; a = a + 1 )
   {
      NSLog(@"value of a: %d\n", a);
   }
 
   return 0;
}

The code above generates the following result.





The Infinite for Loop

An infinite loop's condition never becomes false.

#import <Foundation/Foundation.h>
 
int main ()
{

   for( ; ; )
   {
      NSLog(@"This loop will run forever.\n");
   }

   return 0;
}

nested for loop

#import <Foundation/Foundation.h>
 
int main ()
{
  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);  
 
   return 0;
}

The code above generates the following result.