很多人在写代码的时候,都希望自己能够写出强健的代码,今天,本文主要介绍循环,而循环共有三种,分别为:for,while,do while,各有千秋,选择循环,目的就是让代码更加的简洁,程序更加的智能。
(一)for
例如:用代码显示3个Hallo World!
没有使用for,代码是这样子写的。
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
printf("Hallo World!!\n");
printf("Hallo World!!\n");
printf("Hallo World!!\n");
return 0;
}
运行效果:
使用for,代码如下:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(){
const int number = 3;
int count;
for(count = 1;count <= number;count++){
printf("Hallo World!!\n");
}
return 0;
}
运行效果:
通过上面的案例对比,第一感觉就是第二个案例比较简单的,不过反过来思考一下,如果是要显示出100个Hallo World!呢?那么第二个案例就行不通了,在平时的程序编程应用中,都是要处理很多的数据,使用for也是常常见到,通过对比,就体现出for和没有使用的区别。