Objective-C 嵌套循環
Objective-C語言的編程語言允許使用一個循環的另一循環內。下面的部分顯示了幾個例子來說明這個概念。
語法:
嵌套的for循環語句在C的語法如下:
for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); }
nested while loop 語句的語法在Objective-C編程語言的語句如下:
while(condition) { while(condition) { statement(s); } statement(s); }
嵌套 nested do...while loop 語句語法在Objective-C編程語言的語句如下:
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
", i); } return 0; }
上面的代碼編譯和執行時,它會產生以下結果:
2013-09-07 22:40:01.004 demo[1027] 2 is prime
2013-09-07 22:40:01.005 demo[1027] 3 is prime
2013-09-07 22:40:01.005 demo[1027] 5 is prime
2013-09-07 22:40:01.005 demo[1027] 7 is prime
2013-09-07 22:40:01.005 demo[1027] 11 is prime
2013-09-07 22:40:01.005 demo[1027] 13 is prime
2013-09-07 22:40:01.005 demo[1027] 17 is prime
2013-09-07 22:40:01.005 demo[1027] 19 is prime
2013-09-07 22:40:01.005 demo[1027] 23 is prime
2013-09-07 22:40:01.005 demo[1027] 29 is prime
2013-09-07 22:40:01.005 demo[1027] 31 is prime
2013-09-07 22:40:01.005 demo[1027] 37 is prime
2013-09-07 22:40:01.005 demo[1027] 41 is prime
2013-09-07 22:40:01.005 demo[1027] 43 is prime
2013-09-07 22:40:01.005 demo[1027] 47 is prime
2013-09-07 22:40:01.005 demo[1027] 53 is prime
2013-09-07 22:40:01.005 demo[1027] 59 is prime
2013-09-07 22:40:01.005 demo[1027] 61 is prime
2013-09-07 22:40:01.005 demo[1027] 67 is prime
2013-09-07 22:40:01.005 demo[1027] 71 is prime
2013-09-07 22:40:01.005 demo[1027] 73 is prime
2013-09-07 22:40:01.005 demo[1027] 79 is prime
2013-09-07 22:40:01.005 demo[1027] 83 is prime
2013-09-07 22:40:01.005 demo[1027] 89 is prime
2013-09-07 22:40:01.005 demo[1027] 97 is prime