在上一篇文章的时候,介绍到for,而本篇文章的主要内容则介绍while。
例如:用while循环显示5个Hallo World!
while代码案例1
#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(){
int index = 1;
while(index <= 5)
printf("Hallo World!\n");
return 0;
}
运行结果:
while代码案例2
#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(){
int index = 1;
while(index++ <= 5)
printf("Hallo World!\n");
return 0;
}
运行结果:
在代码案例中使用while的时候可要注意了,那种写法代码运行起来的结果就是无限循环,有时候写程序的时候,难免写错。其实while和for显示出来的效果是一样的,如果没有使用循环的话,那么想要显示n条相同的数据时,就会很麻烦,不但麻烦,还增加了代码量,工作量,这种是划不来的,熟练的使用循环,不但可以简化代码,提高程序质量,提高工作效率。