makaed
makaed

Reputation: 419

'If' statement inside the 'for' loop

In the following Objective-C code, when first inner 'if' statement is satisfied (true), does that mean the loop terminates and go to the next statement?

Also, when it returns to the inner 'for' statement after executing once, does the value of p is again 2, why?

// Program to generate a table of prime numbers

#import <Foundation/Foundation.h>

int main (int argc, char *argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   int p, d, isPrime;

   for ( p = 2; p <= 50; ++p ) {
       isPrime = 1;

       for ( d = 2; d < p; ++d )
            if (p % d == 0)
                isPrime = 0;

       if ( isPrime != 0 )
           NSLog (@”%i ", p);
 }

 [pool drain];
 return 0;
}

Thanks in advance.

Upvotes: 2

Views: 15543

Answers (3)

IronMensan
IronMensan

Reputation: 6831

Your code is equivilant to this:

// Program to generate a table of prime numbers 

import <Foundation/Foundation.h> 

int main (int argc, char *argv[]) 
{ 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    int p, d, isPrime; 

    for ( p = 2; p <= 50; ++p ) { 
        isPrime = 1; 

        for ( d = 2; d < p; ++d ) { 
            if (p % d == 0) { 
                isPrime = 0;
            }
        }

        if ( isPrime != 0 ) { 
            NSLog (@”%i ", p); 
        }
    } 

    [pool drain]; 
    return 0; 
} 

The contents of if and for control statements is the next statement or statement block in braces.

As daveoncode said, you really should use braces.

Upvotes: 1

Mike W.
Mike W.

Reputation: 1375

No, the 'if' statement resolving to true will not break you out of the loop. The loop continues to execute, which is probably why you think p is still 2. It's still 2 because your still in the inner loop.

Upvotes: 2

daveoncode
daveoncode

Reputation: 19578

A loop does not terminate until one of the following happens:

  1. a return is encountered
  2. an exception is raised
  3. a break statement is encountered
  4. the condition of loop evaluates to false

ps. use curly braces, otherwise your code will be impossible to read/debug/mantain

Upvotes: 5

Related Questions