Objective-C 嵌套循环

  • 嵌套循环

    嵌套循环Objective-C编程语言允许在另一个循环中使用一个循环。以下部分显示了一些示例来说明这一概念。
    C中嵌套的for循环语句的语法如下-
    
    for ( init; condition; increment ) {
       for ( init; condition; increment ) {
          statement(s);
       }
       statement(s);
    }
    
    Objective-C编程语言中的嵌套while循环语句的语法如下-
    
    while(condition) {
       while(condition) {
          statement(s);
       }
       statement(s);
    }
    
    Objective-C编程语言中的嵌套do ... while循环语句的语法如下-
    
    do {
       statement(s);
       do {
          statement(s);
       } while( condition );
    
    } while( condition );
    
    关于循环嵌套的最后一点是您可以将任何类型的循环放入任何其他类型的循环中。例如,for循环可以在while循环内,反之亦然。
  • 示例

    以下程序使用嵌套的for循环来查找2到100之间的质数-
    
    #import <Foundation/Foundation.h>
     
    int main () {
       
        /* local variable definition */
       int i, j;
       
       for(i=2; i<100; i++) {
          for(j=2; j <= (i/j); j++)
            if(!(i%j)) break;        // if factor found, not prime
          if(j > (i/j)) NSLog(@"%d is prime\n", i);
       }
     
       return 0;
    }
    
    编译并执行上述代码后,将产生以下结果-
    
    2020-08-04 13:42:38.691 test[2653:2653] 2 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 3 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 5 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 7 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 11 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 13 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 17 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 19 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 23 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 29 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 31 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 37 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 41 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 43 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 47 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 53 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 59 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 61 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 67 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 71 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 73 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 79 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 83 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 89 is prime
    2020-08-04 13:42:38.692 test[2653:2653] 97 is prime