从一个简单的例子——计数开始讨论。 第1页/共45页 5 循环结构 代码清单5-1 --------------------------------------------------------------------------------------------------- #import <Foundation/> // Program to calculate the eighth triangular number int main (int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int triangularNumber; triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8; NSLog (@”The eighth triangular number is %i”, triangularNumber); [pool drain]; return 0; } 输出: The eighth triangular number is 36 第2页/共45页 第5章 循环结构 do语句
break语句
while语句
循环结构
continue语句
小结
第3页/共45页 for语句 代码清单5-2的目的是计算第200位三角数。 代码清单5-2 --------------------------------------------------------------------------------------------------- // Program to calculate the 200th triangular number // Introduction of the for statement #import <Foundation/> int main (int argc, char *argv[]) { ***@autoreleasepool{ int n, triangularNumber; triangularNumber = 0; for ( n = 1; n <= 200; n = n + 1 ) triangularNumber += n; NSLog (@”The 200th triangular number is %i”, triangularNumber); } return 0; } 输出: The 200th triangular number is 20100 第4页/共45页 for语句 用于计算第200位三角数的方法其实与5-1中用于计算第8位三角数的方法是相同的,就是求1到200之间的整数之和。 在执行for语句之前,变量triangularNumber被设置为0。一般来说,在程序使用变量之前,需要将所有的变量初始化为某个值。虽然某些类型的变量将被给定默认值,但是无论如何都应该为变量设置初始值。 for语句提供的机制可使你避免显示地写出1到200之间的每个整数。从某种意义上讲,这条语句将为你生成这些数字。 第5页/共45页 for语句 for语句的一般格式如下: for ( init_expression; loop_condition; loop_expression ) program statement; 圆括号中的3个表达式init_expression,loop_condition和loop_expression建立了程序循环的“环境”。其后的program statement可以是任何合法 的Objective-C程序语句,它们组成循环体。这条语句执行的次数由for语句中设置的参数决定。 第6页/共45页 for语句 for语句的第一部分init_expression,用于在循环开始之前设置初始值