MST

星途 面试题库

面试题:Objective-C中for循环与while循环的应用场景区别

请阐述在Objective-C编程中,for循环和while循环通常分别适用于哪些场景,并各举一个简单的代码示例说明。
23.5万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

for循环适用场景

for循环通常适用于已知循环次数的场景,例如遍历数组、执行固定次数的任务等。

for循环代码示例

NSArray *numbers = @[@1, @2, @3, @4, @5];
for (NSUInteger i = 0; i < numbers.count; i++) {
    NSNumber *number = numbers[i];
    NSLog(@"Number at index %lu is %@", (unsigned long)i, number);
}

while循环适用场景

while循环通常适用于在满足某个条件下持续循环,不确定具体循环次数,直到条件不满足时停止,例如读取文件直到文件末尾、处理用户输入直到满足特定条件等。

while循环代码示例

NSUInteger counter = 0;
while (counter < 5) {
    NSLog(@"Counter is %lu", (unsigned long)counter);
    counter++;
}