C和C++从零开始系列(五)

今天继续C和C++从零开始系列。

前边说了 for 循环,并且从 for 循环的一步步转换为 while 循环。对于C#,java 等语言, 上一篇文章末尾,while 中的条件一般都用 while (true) 来实现。

C和C++是一样的,也可以用 while (true) 来实现。

 1 int main()
 2 {
 3         int a[10] ={0};
 4         int x = 0;
 5         while( true )
 6         {
 7                 if (x >= 10)
 8                         break;
 9                 a[x]=2*x;
10                 x++;
11         }
12         x=0;
13         while ( true )
14         {
15                 if (x >= 10)
16                         break;
17                 printf("The %d element is %d\n", x+1, a[x]);
18                 x++;
19         }
20         return 0;
21 }

这段代码会在编译的时候需要注意:

1. 扩展名为.c, g++ 编译成功

2. 扩展名为.c, gcc 编译需要添加 <stdbool.h> 头文件

3. 扩展名为 .cc,g++和gcc均不需要添加 <stdbool.h> 头文件

4. 在 VS 中,扩展名为 .c ,需要添加 <stdbool.h> 头文件

5. 在 VS 中,扩展名为 .cpp, 不需要添加 <stdbool.h> 头文件

接下来,我们需要把上一篇文章中最初版本的 for 循环替换为 while 循环

 1 int main()
 2 {
 3         int a[10] ={0};
 4         for (int x = 0; x < 10; x++)
 5         {
 6                 a[x]=2*x;
 7         }
 8         for (int x = 0; x < 10; x++)
 9         {
10                 printf("The %d element is %d\n", x+1, a[x]);
11         }
12         return 0;
13 }
 1 int main()
 2 {
 3         int a[10] ={0};
 4         int x = 0;
 5         while( x < 10 )
 6         {
 7                 a[x]=2*x;
 8                 x++;
 9         }
10         x=0;
11         while ( x < 10 )
12         {
13                 printf("The %d element is %d\n", x+1, a[x]);
14                 x++;
15         }
16         return 0;
17 }

将 for 循环的第二个条件放在 while 循环的条件判断中即可实现 for 循环到 while 循环的转换。

while 循环有另一种被称为直到型循环。

我们有如下代码

 1 int main()
 2 {
 3         int x = 0;
 4         do
 5         {
 6                 printf("x*2=%d\n", x*2);
 7                 x++;
 8         }
 9         while(x < 10);
10         return 0;
11 }

这段代码的大致意思是输出 x*2 的结果,直到 x < 10 不成立时结束。

输出结果为

[daniel@daniel loop]$ ./dowhile 
x*2=0
x*2=2
x*2=4
x*2=6
x*2=8
x*2=10
x*2=12
x*2=14
x*2=16
x*2=18
View Code

当型循环和直到型循环的区别是直到型循环至少会执行一次 do 代码块的内容。比如以下代码

 1 int main()
 2 {
 3         int x = 100;
 4         do
 5         {
 6                 printf("x*2=%d\n", x*2);
 7                 x++;
 8         }
 9         while(x < 10);
10         return 0;
11 }

从一开始,x 的值就不满足 while 的条件判断,运行时我们发现 do 中的代码块仍然会执行。但是只执行了一次。

[daniel@daniel loop]$ gcc dowhile.c -o dowhile
[daniel@daniel loop]$ ./dowhile 
x*2=200

这是两种循环的区别,如果我们用当型循环时,不会输出任何字符。

猜你喜欢

转载自www.cnblogs.com/danielhu/p/12114464.html