'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 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:
- a return is encountered
- an exception is raised
- a break statement is encountered
- 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.
精彩评论