1、for循环与while循环的写法的转换
(1)for循环
for循环写法
for (init-expression; test-expression; update-expression)
{
statement(s);
}
for循环转换为while循环写法
init-expression;
while (test-expression)
{
statement(s);
update-expression;
}
(2)while循环
while循环写法
while (test-expression)
{
body;
}
while循环转换为for循环写法
for ( ; test-expression;)
{
body;
}
2、for循环需要3个表达式,不过可以为空。省略for循环中的测试表达式时,测试结果将为true,因此循环将一直运行下去。
3、for循环与while循环的三个差别
(1)for循环省略了测试条件时,将认为条件为true;
(2)for循环中,可使用初始化语句声明一个局部变量,但while循环中不能这样做;
(3)如果循环体中包括continue语句情况将不同,continue将在第六章讨论。
通常,for循环用来为循环计数;无法预先知道循环将执行的次数时,使用while循环。