开发者

'If' statement inside the 'for' loop

开发者 https://www.devze.com 2023-04-05 23:53 出处:网络
In the following Objective-C code, when first inner \'if\' statement is satisfied (true), does that mean the loop terminates and go to t开发者_如何转开发he next statement?

In the following Objective-C code, when first inner 'if' statement is satisfied (true), does that mean the loop terminates and go to t开发者_如何转开发he 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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号