Objective-C编程语言允许在另一个循环中使用一个循环。以下部分显示了几个例子来说明这个概念。
语法
Objective-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 () {
/* 局部变量定义 */
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;
}
执行上面示例代码,得到以下结果:
2018-11-14 07:14:35.503 main[60729] 2 is prime
2018-11-14 07:14:35.505 main[60729] 3 is prime
2018-11-14 07:14:35.505 main[60729] 5 is prime
2018-11-14 07:14:35.505 main[60729] 7 is prime
2018-11-14 07:14:35.505 main[60729] 11 is prime
2018-11-14 07:14:35.506 main[60729] 13 is prime
2018-11-14 07:14:35.506 main[60729] 17 is prime
2018-11-14 07:14:35.506 main[60729] 19 is prime
2018-11-14 07:14:35.506 main[60729] 23 is prime
2018-11-14 07:14:35.506 main[60729] 29 is prime
2018-11-14 07:14:35.506 main[60729] 31 is prime
2018-11-14 07:14:35.506 main[60729] 37 is prime
2018-11-14 07:14:35.506 main[60729] 41 is prime
2018-11-14 07:14:35.506 main[60729] 43 is prime
2018-11-14 07:14:35.506 main[60729] 47 is prime
2018-11-14 07:14:35.506 main[60729] 53 is prime
2018-11-14 07:14:35.506 main[60729] 59 is prime
2018-11-14 07:14:35.506 main[60729] 61 is prime
2018-11-14 07:14:35.506 main[60729] 67 is prime
2018-11-14 07:14:35.506 main[60729] 71 is prime
2018-11-14 07:14:35.506 main[60729] 73 is prime
2018-11-14 07:14:35.506 main[60729] 79 is prime
2018-11-14 07:14:35.506 main[60729] 83 is prime
2018-11-14 07:14:35.506 main[60729] 89 is prime
2018-11-14 07:14:35.506 main[60729] 97 is prime