'If' statement inside the 'for' loop

11,637

Solution 1

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.

Solution 2

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

Solution 3

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.

Share:
11,637
makaed
Author by

makaed

Updated on June 05, 2022

Comments

  • makaed
    makaed almost 2 years

    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.