学习完while,会发现很多循环是不确定的,即不知道循环将会运行多少次
/*summing.c -- 根据用户输入的整数求和*/
#include <stdio.h>
int main (void)
{
long num;
long sum = 0L;//sum初始化为0
int status;
printf("Please enter an integer to be summed ");
printf("(q to quit):");
status = scanf("%ld",&num);
while(status == 1)
{
sum = sum + num;
printf("Please enter next integer (q to quit):");
status = scanf("%ld",&num);
}
printf("Those integers sum to %ld.\n", sum);
return 0;
}
就像这个程序,需要用户自己输入的,无法得知用户将会输入多少次。
预之相对的还有一种计数循环,这类循环在程序执行之前就知道程序要执行多少次
/* sweetile.c -- 一个计数循环*/
#include <stdio.h>
int main (void)
{
const int NUMBER = 10;
int count = 1;
while(count <= NUMBER)
{
printf("Be my Valentine!\n");
count ++;
}
return 0;
}
这道程序输出结果如下:
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
Be my Valentine!
一共10次输出Be my Valentine!在程序中也有所体现。
这是循环的两种分类,顺手提一下。
for循环
接下来研究for循环,先演示使用for循环改动上面的案例
#include <stdio.h>
int main (void)
{
const int NUMBER = 10;
int count = 1;
for(count = 1; count <= NUMBER; count ++)
{
printf("Be my Valentine!\n");
}
return 0;
}
从上面的程序中我们可以观察到for循环的格式,关键字for后面的圆括号中有3个表达式,分别用分号隔开。第1个表达式是初始化,只会在for循环开始时执行一次;第2个表达式是测试条件,在执行循环之前对表达式求值,真则继续,假则结束;第3个表达式执行更新,每次循环结束时求值,更新计数。圆括号中的表达式还叫做控制表达式,控制整个循环,他们都是完整的表达式,并且每个表达式的副作用都发生在对下一个表达式之前。
给出一个书中的案例,用for循环打印立方表。
/*for_cube.c -- 立方表*/
#include <stdio.h>
int main (void)
{
int n;
printf(" n n^2 n^3\n");
for(n = 1; n <= 9; n++)
{
printf("%5d %5d %7d\n", n, n*n, n*n*n);
}
return 0;
}
输出结果如下:
n n^2 n^3
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
这里演示了for循环的使用。
之所以说for循环更加灵活,是因为它有三个表达式。使用for循环的好处在于,还有9种用法,下面一一介绍
- 可以使用递减运算符来递减计数器,就是倒计时
/*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!
- 可以让计数器递增6(或者其他数)
/*for_6s.c -- 计数器加六*/
#include <stdio.h>
int main (void)
{
int n;
for (n = 5; n < 20; n = n+6)
{
printf("%5d ", n);
}
printf("\n over\n");
return 0;
}
5 11 17
over
- 可以用字符代替数字计数
/*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 c is 99.
。。。。。。此处略去20条。。。。。。
The ASCII value for x is 120.
The ASCII value for y is 121.
The ASCII value for z is 122.
- 除了测试迭代次数外,还可以测试其他条件。如在for_cube中,可以把:
for(n = 1; n <= 9; n++)改成
for(n = 1; n*n*n <= 729; n++)
如果与控制循环次数相比你更在意循环的大小,就可以这么用。
- 可以让递增的量几何增长,而不是算数增长。还用for_cube举例
for(n = 1; n <= 9; n++)改成
for(n = 1; n <= 9; n = n * 2)
这样每次增长2倍,而不是一个固定值。
- 从上面几个例子看来,第3 个表达式可以使用任意合法表达式,无论是什么表达式,每一次迭代都会更新该表达式的值。
- 省略一个或多个表达式也是可以的,只有循环体中包含能结束循环的语句即可,但是分号不能省略。
- 第1 个表达式不一定是给变量赋值,也可以使用printf()。记住执行循环的其他部分之前,只对第1个表达式求一次值,或执行一次。
- 循环体中的行为可以改变循环头中的表达式。可能有点难理解,不要担心,后面的章节会有解释。
OVER!