六、C控制语句: 循环
4. 不确定循环和计数循环
// sweetiel.c -- 一个计数循环
#include <stdio.h>
int main(void)
{
const int NUMBER = 22; // 初始化
int count = 1;
while (count <= NUMBER) // 测试
{
printf("Be my Valuentine!\n"); // 行为
count++; // 更新计数
}
return 0;
}
5. for 循环
// sweetie2.c -- 使用 for 循环的计数循环
#include <stdio.h>
int main(void)
{
const int NUMBER = 22;
int count;
for (count = 1; count <= NUMBER; count++)
printf("Be my Valuentine!\n");
return 0;
}
/* for_cube.c -- 使用 for 循环创建一个立方表 */
#include <stdio.h>
int main(void)
{
int num;;
printf(" n n cubed\n");
for (num = 1; num <=6; num++)
printf("%5d %5d\n", num, num*num*num);
return 0;
}
// n n cubed
// 1 1
// 2 8
// 3 27
// 4 64
// 5 125
// 6 216
5.1 利用 for 的灵活性
■ 可以使用递减运算符来递减计数器:
/* for_down.c */
#include <stdio.h>
int main(void)
{
int secs;
for (secs = 5; secs > 0; secs--)
printf("%d seconds!\n", secs);
printf("We have ignition!\n");
return 0;
}
//5 seconds!
//4 seconds!
//3 seconds!
//2 seconds!
//1 seconds!
//We have ignition!
■ 可以让计数器递增2、10等:
/* for_13s.c */
#include <stdio.h>
int main(void)
{
int n; // count by 13s from 2
for (n = 2; n < 60; n = n + 13)
printf("%d \n", n);
return 0;
}
//2
//15
//28
//41
//54
■ 可以用字符代替数字计数:
/* for_char.c */
#include <stdio.h>
int main(void)
{
char ch;
for (ch = 'a'; ch <= 'z'; ch++)
printf("The ASCII value for %c is %d.\n", ch, ch);
return 0;
}
//The ASCII value for a is 97.
//The ASCII value for b is 98.
//...
//The ASCII value for x is 120.
//The ASCII value for y is 121.
//The ASCII value for z is 122.
■ 除了测试迭代次数外,还可以测试其他条件。在for_cube程序中,可以把:
for (num = 1; num <= 6; num++)
替换成:
for (num = 1; num*num*num <=216; num++)
■ 可以让递增的量几何增长,而不是算术增长。
/* for_geo.c */
#include <stdio.h>
int main(void)
{
double debt;
for (debt = 100.0; debt < 150.0; debt = debt * 1.1)
printf("Your debt is now $%.2f.\n", debt);
return 0;
}
//Your debt is now $100.00.
//Your debt is now $110.00.
//Your debt is now $121.00.
//Your debt is now $133.10.
//Your debt is now $146.41.
■ 第3个表达式可以使用任意合法的表达式。
/* for_wild.c */
#include <stdio.h>
int main(void)
{
int x;
int y = 55;
for (x = 1; y <= 75; y = (++x * 5) + 50)
printf("%10d %10d\n", x, y);
return 0;
}
// 1 55
// 2 60
// 3 65
// 4 70
// 5 75
■ 可以省略一个或多个表达式(但是不能省略分号),只要在循环中包含能结束循环的语句即可。
/* for_none.c */
#include <stdio.h>
int main(void)
{
int ans, n;
ans = 2;
for (n = 3; ans <= 25; )
ans = ans * n;
printf("n = %d; ans = %d.\n", n, ans);
return 0;
}
//n = 3; ans = 54.
下面循环会一直运行:
for (; ; )
printf("I want some action\n");
■ 第一个表达式不一定是给变量赋初值,也可以使用printf()。
/* for_show.c */
#include <stdio.h>
int main(void)
{
int num = 0;
for (printf("Keep entering numbers!\n"); num != 6; )
scanf("%d", &num);
printf("That's the one I want!\n");
return 0;
}
//Keep entering numbers!
//3
//5
//8
//6
//That's the one I want!