Header Ads

Loop Control Statements - objective c

Loop control statement change execution from its normal sequence. When execution leaves a scope, all automatic object that were created in that scope are destroyed.

Objective C supports the following statements.
Control statement Description
break statement Termnates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
continue statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Infinite loop A loop becomes infinite loop if a condition never become false.


Break statement

The break statement in objective C programming language has the following two usage.
  1. When the break statement is encountered inside the loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
  2. It can be used to terminate a case in the switch statement.
 If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
Syntax:
            break;

Example

#import<Foundation/Foundation.h>
int main()
{
     int a = 10;
     while (a<20)
     {
          NSLog(@"value of a :%d \n", a);
          a++;
          if( a> 15)
          {
                break;
           }
       }
       return 0;
 }
      

  Continue statement

 The continue statement in objective C programming language,works somewhat like the break statement. Instead of forcing termination, however continue forces the next iteration of the loop to take place, skipping ant code in between.

For the for loop continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control pass to the conditional tests.

Syntax
             continue; 

Example

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

The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that from the loop are required, you can make an endless loop by leaving the conditional expression empty.

#import <Foundation/Foundation.h>
int main()
{
      for (  ;  ;   )
      {
               NSLog(@"This loop will run forever, \n");
      }
      return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an intialization  and increment expression, but Objective C programmers more commonly use the for(;;) construct to signify an infinite loop.

No comments:

Powered by Blogger.